gpt4 book ai didi

haskell - 为什么 foldr 给我这个错误?

转载 作者:行者123 更新时间:2023-12-02 07:20:24 24 4
gpt4 key购买 nike

foldr (\x ante->[x]:[ante]) [4] [1,2,3]

所以如果我得到正确的 foldr,第一次函数 (\x ante->[x]:[ante]) 会做一些事情,我会调用这个函数 f,它将是在:

   f 3 [4] = [3]:[[4]] = [[3],[4]]

为什么函数不这样做?它显示此错误:

* Occurs check: cannot construct the infinite type: a ~ [a]
Expected type: [a]
Actual type: [[a]]
* In the expression: [x] : [ante]
In the first argument of `foldr', namely
`(\ x ante -> [x] : [ante])'
In the expression: foldr (\ x ante -> [x] : [ante]) [4] [1, 2, 3]
* Relevant bindings include
ante :: [a] (bound at testefoldr.hs:51:21)
x :: a (bound at testefoldr.hs:51:19)
folder4 :: [a] (bound at testefoldr.hs:51:1)
|51 | folder4 = foldr (\x ante->[x]:[ante]) [4] [1,2,3]

我创建了一个 .hs 然后我把

folder4 = foldr (\x ante->[x]:[ante]) [4] [1,2,3]

用于更快的测试。这就是错误中有folder4的原因。

最佳答案

foldr 函数的类型为:

foldr :: <b>(a -> b -> b)</b> -> b -> [a] -> b

这意味着它将要折叠的列表的一个元素(type a)和累加器(type b)作为输入,并返回一个累加器(再次键入 b)。如果 Haskell 不是静态类型的,它每次都会将累加器包装在一个新列表中。所以它会导致:

[4]
-> [[3],[4]]
-> [[2],[[3],[4]]]
-> [[1],[[2],[[3],[4]]]]

这没有意义。

这里有两个问题:

  1. 如果 ante 的类型为 b,则 [x] : [ante] 的类型为 [b] ;和
  2. 初始累加器 [4] 的类型不是 foldr 的结果。

所以你可以通过写来解决这个问题:

foldr (\x ante->[x]:ante) [[4]] [1,2,3]

关于haskell - 为什么 foldr 给我这个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com