简体   繁体   中英

F# Pattern Match on Seq.Length

I'm learning some F# and messing around with pattern matching. I have the below code.

Seq.distinct [1; 1; 2] 
   |> match Seq.length with 
      | 1 -> printf "one" 
      | 2 -> printf "two" 
      | _ -> printf "other"

But when running or trying to compile it gives the error of:

This expression was expected to have type
'a -> int 
but here has type
int

I'm not quite sure what the issue is and what exactly is being asked. I'm sure I'm missing something simple, but is there another way I should be doing this?

You could do either this:

match Seq.distinct [1; 1; 2] |> Seq.length with 
| 1 -> printf "one" 
| 2 -> printf "two" 
| _ -> printf "other"

or this:

Seq.distinct [1; 1; 2] 
|> Seq.length
|> function
    | 1 -> printf "one" 
    | 2 -> printf "two" 
    | _ -> printf "other"

But, as is, you're piping the output from Seq.distinct to a match expression and not Seq.length as you intend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM