SML 中函数的类型
谁能向我解释为什么下面给出的函数类型是
<代码>('a * 'b -> 'b) -> 'b-> '列表-> 'b?
函数是:
fun foldr f b [] = b
| foldr f b (x::xs) = f (x, (foldr f b xs))
当我查看这个函数时,我发现类型应该是 ('a * 'b -> 'b) -> 'b
因为我们有一个函数 f
,它接受一个元组并仅在 'b
返回,并且在基本情况下我们返回 'b
。
Can anyone explain to me why the type of the function given below is('a * 'b -> 'b) -> 'b -> 'a list -> 'b
?
The function is:
fun foldr f b [] = b
| foldr f b (x::xs) = f (x, (foldr f b xs))
When I look at this function, I find the type should just be ('a * 'b -> 'b) -> 'b
since we have a function f
which is taking in a tuple and just returning at 'b
and also in the base case we return the 'b
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要确定函数的类型,过程基本上是这样的:
给定一个函数,
假设所有参数和返回值的类型都是未知的。
首先,我们可以看到
b
(arg2)与foldr
(return)的返回类型相同,而(arg3)是一些未知类型的列表。x
和xs
组成 (arg3) 列表。那么
f
(arg1) 是一个接受 2 元组并返回与foldr
返回 (return) 相同类型的函数。元组的第一项与x
类型相同。元组的第二项与foldr
(返回)的返回类型相同。到目前为止,这些类型也适用于对foldr
的递归调用。它无法进一步简化,因此我们有以下类型:
foldr:
('a * 'b -> 'b) -> 'b-> '列表-> 'b
To determine the type of a function, the process basically goes like this:
Given a function,
assume all types of the parameters and return value are unknown.
First of all, we can see that
b
(arg2) is the same as the return type offoldr
(return) and (arg3) is a list of some unknown type.x
andxs
make up the list of (arg3).Then
f
(arg1) is a function that takes a 2-tuple and returns the same type asfoldr
returns (return). The first item of the tuple is the same type ofx
. The second item of the tuple is the same type of the return type offoldr
(return). The types also hold so far for the recursive call tofoldr
.It cannot be simplified any further so we have the type:
foldr:
('a * 'b -> 'b) -> 'b -> 'a list -> 'b
我认为上面的
foldr
代码是不正确的;它应该是也就是说,它不应该传入参数元组,而是像往常一样传入累加器和对
foldr
的递归调用作为参数。至于类型的来源,请记住
foldr
接受三个参数:假设累加器的类型为
'b
,列表的类型为'blist
。我们知道函数的总体返回类型应该是'b
,因为我们现在看看
f
的类型是什么。我们有这样的:它接受列表的第一个元素和累加器,然后生成必须为
'b
类型的内容。列表的类型为'a list
,累加器的类型为'b
,因此函数的类型为('a * 'b -> 'b)< /代码>。
综上所述,该函数的类型是
“Which is what is reporting”。
I think that the above code for
foldr
is incorrect; it should beThat is, it should not be passing in a tuple of arguments, but rather passing in the accumulator and the recursive call to
foldr
as arguments as usual.As for where the type comes from, remember that
foldr
takes in three parameters:Let's say that the accumulator has type
'b
and that the list has type'blist
. We know that the overall return type of the function should be'b
, because we haveLet's now see what the type of
f
is. We have this:This takes in the first element of the list and the accumulator, then produces something that must be of type
'b
. The list has type'a list
and the accumulator has type'b
, so the function has type('a * 'b -> 'b)
.Summing this up, the type of the function is
Which is what is being reported.