【问题标题】:type inference of (>>)(>>) (function composition)(>>)(>>) 的类型推断(函数组合)
【发布时间】:2014-05-03 18:42:50
【问题描述】:

我在某处看到过(抱歉,我找不到参考)这个运算符组合:

(>>)(>>)

其中(>>): (('a -> 'b) -> ('b -> 'c) -> 'a -> 'c) - (>>)the function composition operator

我发现简单的例子很容易理解。例如(>>)f,其中f: i -> i(>>)(i -> i) 变为 (i -> 't) -> i -> 't。这是因为('a -> 'b) 被柯里化了,'b 被推断为i't 仍然是一个泛型类型。

我不太明白(>>)(>>)

用途

(>>)(>>)(<<)(<<) 将用于什么用途?

为什么需要明确论证?

> (>>)(>>);;

  (>>)(>>);;
  -^^^^^^

C:\Users\...\Temp\stdin(3,2): error FS0030: Value restriction. The value 'it' has been inferred to have generic type
    val it : (((('_a -> '_b) -> '_c -> '_b) -> '_d) -> ('_c -> '_a) -> '_d)    
Either make the arguments to 'it' explicit or, if you do not intend for it to be generic, add a type annotation.

根据错误消息的建议:

> let strangeFun arg = (>>)(>>) arg;;

val strangeFun : arg:((('a -> 'b) -> 'c -> 'b) -> 'd) -> (('c -> 'a) -> 'd)

【问题讨论】:

    标签: f# type-inference


    【解决方案1】:

    过去这里有几种关于价值限制的解释; here 是我写的一个解释为什么它是必要的。为了完整起见,我将在此处复制如果删除值限制将不正确的示例代码:

    let f : 'a -> 'a option =
        let r = ref None
        fun x ->
            let old = !r
            r := Some x
            old
    
    f 3           // r := Some 3; returns None : int option
    f "t"         // r := Some "t"; returns Some 3 : string option!!!
    

    至于(>>)(>>) 的用途,我承认我不知道。然而,有一个看起来相似但有用的函数,即(<<) << (<<)(在 Haskell 中更广为人知的是 (.).(.)),它返回一个类似的组合运算符,其第二个和返回的函数可以采用 两个 参数一个。

    let (<<<<) f = ((<<) << (<<)) f;;
    
    // val ( <<<< ) : f:('a -> 'b) -> (('c -> 'd -> 'a) -> 'c -> 'd -> 'b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 2021-12-15
      • 2020-02-16
      • 1970-01-01
      • 2022-01-07
      • 2021-03-09
      相关资源
      最近更新 更多