如何阅读F#类型签名? [英] How to read F# type signatures?

查看:74
本文介绍了如何阅读F#类型签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为F#类型签名表示法而苦苦挣扎.例如,假设您具有Fold函数:

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 have this type signature:

('a -> 'b -> 'a) -> 'a -> list<'b> -> 'a

我会读为

具有三个参数的函数:

  • 接受'a,'b并返回a'的函数
  • 一个'a
  • "b
  • 的列表
  • a function that takes an 'a, a 'b and returns an a'
  • an 'a
  • a list of 'b

并返回一个'a.

但是,对于我的穴居人的大脑来说,将其表达为

But then it would make more sense for my cavemen brain to express it as

('a, 'b -> 'a), 'a, list<'b> -> 'a

我肯定有一个语义上的原因,为什么用箭头分隔参数的方式与函数返回类型的方式完全相同,但是以某种方式我却错过了它,并且到目前为止在书/文章中都没有找到明确的解释.每次我看到类型签名时,我都必须花很多时间来理解它.我觉得我只是缺少使解密"变得显而易见的那一小部分拼图.

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. Every time I see a type signature I have to stop quite a bit of time to understand it. I feel like I'm just missing that little piece of the puzzle that makes the "decryption" obvious.

有人可以启发我吗?

推荐答案

我确定这是语义上的原因 为什么参数用 箭头与 函数返回类型,但是我不知何故 错过了,没有找到一个明确的 到目前为止,在书籍/文章中都有解释.

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

考虑一下,add4签名与此等效:

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.

这篇关于如何阅读F#类型签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆