gpt4 book ai didi

haskell - 发生检查: cannot construct the infinite type

转载 作者:行者123 更新时间:2023-12-02 10:53:45 26 4
gpt4 key购买 nike

我要处理的任务如下:

pipe [f1,...,fn] x should return f1(f2(...(fn x)))



这是我的代码:
pipe :: [(a -> a)] -> (a -> a)
pipe fs = foldl' f base fs
where
f a x = a (x)
base = (\x -> x)

我认为这在遍历函数列表时是有意义的,但是,编译器告诉我:
tutorial.hs:45:20: error:
• Occurs check: cannot construct the infinite type: a ~ a -> a
Expected type: (a -> a) -> (a -> a) -> a -> a
Actual type: ((a -> a) -> a -> a) -> (a -> a) -> a -> a
• In the first argument of ‘foldl'’, namely ‘f’
In the expression: foldl' f base fs
In an equation for ‘pipe’:
pipe fs
= foldl' f base fs
where
f a x = a (x)
base = (\ x -> x)
• Relevant bindings include
fs :: [a -> a] (bound at tutorial.hs:45:6)
pipe :: [a -> a] -> a -> a (bound at tutorial.hs:45:1)
|
45 | pipe fs = foldl' f base fs
| ^
Failed, no modules loaded.

我是Haskell的新手,感谢您的提前帮助:)

最佳答案

你可以做

pipe :: [a -> a] -> (a -> a)
pipe = foldr (flip (.)) id
foldrfoldl之间有区别。

您的 base函数等效于 id

在您的版本中, f的定义不正确。它应该具有两个函数并返回一个新函数。

你可以写成
pipe :: [(a -> a)] -> (a -> a)
pipe fs = foldl f id fs
where
f g h = g . h
base = (\x -> x)

要么
pipe :: [(a -> a)] -> (a -> a)
pipe fs = foldl f id fs
where
f g h a = h (g a)
base = (\x -> x)

如果所有函数都是可交换的,则使用 foldrfoldl没什么区别,否则您需要正确选择 foldrfoldl

关于haskell - 发生检查: cannot construct the infinite type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52564838/

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