为什么这个f#代码不能编译?

时间:2017-09-27 11:04:34

标签: f#

我希望它是一个接受两个字符串并返回整数选项的函数。

 let helper (f : string -> string -> bool * int) = f >> function
    | (true, item) -> Some item
    | (false, _) -> None

2 个答案:

答案 0 :(得分:3)

通过扩展代码可以更容易解释,因此传递/组合的功能较少。

让我们删除撰写运算符>>并使用管道|>代替,添加一个明确的aString参数:

let helper (f : string -> string -> bool * int) aString =
    f aString |> function
    | (true, item) -> Some item
    | (false, _) -> None

现在让我们使用fun而不是function使用显式参数x

let helper (f : string -> string -> bool * int) aString =
    f aString
    |> fun x ->
        match x with
        | (true, item) -> Some item
        | (false, _) -> None

现在让我们通过内联fun

来完全删除管道
let helper (f : string -> string -> bool * int) aString =
    match (f aString : string -> bool * int) with
    | (true, item) -> Some item
    | (false, _) -> None

此代码与您开始时的代码相同。 f aStringf函数,只有一个字符串应用于它。由于currying,此表达式的类型为string -> bool * int。我在上面的代码中添加了一个类型注释来证明这一点。在产生bool * int的结果之前,需要提供另一个字符串。

答案 1 :(得分:1)

f接受两个参数。 >>只会计算一个参数。您可以通过以下方式编写来编译它:

let helper (f : string -> string -> bool * int) =
      fun a -> f a >> function
                      | (true, item) -> Some item
                      | (false, _) -> None

或者您可以在函数签名本身中包含第一个参数,如下所示:

let helper (f : string -> string -> bool * int) a = f a >> function
    | (true, item) -> Some item
    | (false, _) -> None