Haskell FlatMap [英] Haskell FlatMap
问题描述
flatmap ::(t - > a) - > [t] - > [a]
flatmap _ [] = []
flatmap f(x:xs)= fx:flatmap f xs
实现了地图部分,而不是平面。
我做出的大部分修改导致令人沮丧和相当无关的
发生检查:无法构造无限类型:a = [a]
泛化'flatmap'的类型
错误
我缺少什么? p>
当您指定的类型签名与功能的实际类型不匹配时,会发生此类错误。因为你没有显示导致错误的代码,所以我必须猜测,但我认为你将它改成了这样的一种:
flatmap _ [] = []
flatmap f(x:xs)= fx ++ flatmap f xs
这样做是完全正确的。但是如果您忘记了更改类型签名,将会发生以下情况:
类型检查器会看到您对 fx的结果使用++
和 flatmap f xs
。由于 ++
在同一类型的两个列表上工作,因此类型检查器现在知道两个表达式都必须对同一类型的列表进行求值。现在,类型检查器也知道 flatmap f xs
将返回类型为 [a]
的结果,所以 fx
也必须有类型 [a]
。然而,在类型签名中,它表示f具有类型 t - >一个
,所以 f x
必须输入 a
。这导致类型检查器得出结论, [a] = a
这是一个矛盾,并导致您看到的错误消息。
如果将类型签名更改为 flatmap ::(t - > [a]) - > [t] - > [a]
(或删除它),它将工作。
I am a beginner interested in Haskell, and I have been trying to implement the flatmap (>>=) on my own to better understand it. Currently I have
flatmap :: (t -> a) -> [t] -> [a]
flatmap _ [] = []
flatmap f (x:xs) = f x : flatmap f xs
which implements the "map" part but not the "flat".
Most of the modifications I make result in the disheartening and fairly informationless
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `flatmap'
error.
What am I missing?
An error like this happens when the type signature you specify does not match the actual type of the function. Since you didn't show the code that causes the error, I have to guess, but I presume you changed it to something like this:
flatmap _ [] = []
flatmap f (x:xs) = f x ++ flatmap f xs
Which as it happens, is perfectly correct. However if you forgot to also change the type signature the following will happen:
The type checker sees that you use ++ on the results of f x
and flatmap f xs
. Since ++
works on two lists of the same type, the type checker now knows that both expressions have to evaluate to lists of the same type. Now the typechecker also knows that flatmap f xs
will return a result of type [a]
, so f x
also has to have type [a]
. However in the type signature it says that f has type t -> a
, so f x
has to have type a
. This leads the type checker to conclude that [a] = a
which is a contradiction and leads to the error message you see.
If you change the type signature to flatmap :: (t -> [a]) -> [t] -> [a]
(or remove it), it will work.
这篇关于Haskell FlatMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!