Seq.Length上的F#模式匹配

时间:2014-05-19 21:29:43

标签: f# pattern-matching

我正在学习一些F#并搞乱模式匹配。我有以下代码。

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

但是在运行或尝试编译时会出现以下错误:

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

我不太确定问题是什么,究竟是什么问题。我确定我错过了一些简单的事情,但我还有另一种方法吗?

1 个答案:

答案 0 :(得分:8)

你可以这样做:

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

或者这个:

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

但是,按照您的意图,您将输出从Seq.distinct传递到match表达式,而不是Seq.length