【发布时间】:2021-11-08 11:14:31
【问题描述】:
这是我写的代码:
multiApp :: (a -> a) -> [a -> a] -> a -> [a]
multiApp f [] x = []
multiApp f gs x = f $ multiAppi gs x
multiAppi :: [a -> a] -> a -> [a]
multiAppi [] x = []
multiAppi gs x = ((head gs) x) : multiAppi (tail gs) x
我正在尝试将函数列表用于一个值,然后将函数 f 用于该列表。
例子:
multiApp id [] 7 ==> []
multiApp id [id, reverse, tail] "This is a test" ==> ["This is a test","tset a si sihT","his is a test"]
multiApp id [(1+), (^3), (+2)] 1 ==> [2,1,3]
multiApp sum [(1+), (^3), (+2)] 1 ==> 6
multiApp reverse [tail, take 2, reverse] "foo" ==> ["oof","fo","oo"]
multiApp concat [take 3, reverse] "race" ==> "racecar"
这里是答案:
Set3a.hs:269:34: error:
* Occurs check: cannot construct the infinite type: a ~ [a]
* In the second argument of `(:)', namely `multiAppi (tail gs) x'
In the expression: ((head gs) x) : multiAppi (tail gs) x
In an equation for `multiAppi':
multiAppi gs x = ((head gs) x) : multiAppi (tail gs) x
* Relevant bindings include
x :: a (bound at Set3a.hs:269:14)
gs :: [a -> a] (bound at Set3a.hs:269:11)
multiAppi :: [a -> a] -> a -> a (bound at Set3a.hs:268:1)
|
269 | multiAppi gs x = ((head gs) x) : multiAppi (tail gs) x
| ^^^^^^^^^^^^^^^^^^^^^
什么无限类型?什么???
编辑: 现在代码如下所示:
multiApp :: ([a] -> b) -> [a -> a] -> a -> b
multiApp f gs x = f $ multiAppi gs x
multiAppi :: [a -> a] -> a -> [a]
multiAppi [] x = []
multiAppi (g:gs) x = g x : multiAppi gs x
求和函数的错误如下:
set3test.hs:232:42: 错误:
* 无法匹配类型Int' with [Int]'
预期类型:Int -> Int
实际类型:[Int] -> Int
* 在表达式中:head
在multiApp', namely [head, last]' 的第二个参数中
在(?==)', namely multiApp 的第一个参数中 (sum :: [Int] -> Int) [head, last] [1 :: Int, 2, 3, 4]'
|
232 | multiApp (sum::[Int]->Int) [head, last] [1::Int,2,3,4] ?== 5
| ^^^^
而且这个 stackoverflow 需要更少的代码和更多的 cmets。我不知道如何评论这个......
【问题讨论】:
-
我无法重现此错误,您的
multiApp有问题,但multiAppi没有问题。根据错误消息,您使用了[a -> a] -> a -> a而不是[a -> a] -> a -> [a]。 -
multiApp f gs x = f $ multiAppi gs x似乎很奇怪。你将f申请到[a]? -
@MateenUlhaq:根据示例,
f应该是[a] -> b类型,multiApp应该是([a] -> b) -> [a -> a] -> a -> b,因此它是“map reduce”的某种变体。 -
"infinite type" 意味着您的代码只对等于
[a]的类型a有意义——这意味着a = [a] = [[a]] = [[[a]]] = ...,即a应该是list-of-lists-of-lists-of... 无限多次。此错误可以由例如表达式x == x:y触发:这里==要求x和x:y具有相同的类型,但如果我们有x :: a那么(x:y) :: [a]因此我们也有@987654349 @,强制a = [a]并触发无限类型错误。 -
我正用头撞桌子。令人沮丧。
标签: haskell