How to read F# type signatures?

后端 未结 4 869
死守一世寂寞
死守一世寂寞 2021-02-13 10:37

I\'m struggling with the F# type signature notation. For example let\'s say you have a Fold function:

let rec Fold combine acc l =
...

that may

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 11:32

    I'm sure there is a semantic reason why parameters are separated with an arrow exactly the same way as the function return type, but somehow I'm missing it and didn't found a clear explanation in books/articles so far.

    You're reading of the first function is correct. For instant deciphering, type signatures are expressed like this:

    val functionName = inputType1 -> inputType2 -> ... -> inputTypeN -> returnType
    

    Generally, arrow notation indicates a function is curry-able.

    // val add4 : int -> int -> int -> int -> int
    let add4 a b c d = a + b + c + d;;
    
    // val f : (int -> int)
    let f = add4 1 2 3 // returns (int -> int) waiting for last argument
    

    Because the function is curried, you can technically write it like this:

    // val add4 : int -> int -> int -> int -> int
    let add4 = (fun a -> (fun b -> (fun c -> (fun d -> a + b + c + d))));;
    
    // val f : (int -> int)
    let f = fun x -> add4 1 2 3 x
    

    If you think about it, the add4 signature is equivalent to this:

    val add4 : int -> (int -> (int -> (int -> int) ) )
    

    I believe we use arrow notation because it resembles the structure of the function when we explicitly curry arguments as shown above.

提交回复
热议问题