[英]“Cannot create infinite type” error in Haskell
我想知道为什么Haskell会接受这个
perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]
但不会接受:
perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]
它抱怨说
[1/1]编译Main(abc.hs,解释)
Occurs check: cannot construct the infinite type: t = [t] Expected type: t -> [t] Inferred type: [t] -> [[a]] In the second argument of `(:)', namely `(perms y)' In the expression: x : (perms y)
我能理解它的内容,我不能理解为什么第一个是好的而第二个不是!
编辑:啊,我当然也有
perms [] = [[]]
在顶部。
谢谢
在第一个表达式中,你有x:y
,这意味着,如果x :: a
则y :: [a]
。 在x : perms y
if x :: a
那么它必须是perms y :: [a]
,但是perms y :: [[a]]
(排列列表)。 Typechecker试图统一[a]
和[[a]]
并失败。
我的大脑疼,我不是专家,但我想:
在
perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]
perms(takeOut i xs)是一个列表列表。 x被分配到该列表的每个元素上。 Perms作为一个整体在列表中被调用,因此perms是一个采用列表的函数。
在
perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]
(takeOut i xs)是一个列表,对于该列表的每个元素,x被分配到该元素的perms上。 在列表的每个元素上调用Perms,因此perms是一个函数。
只有前一种情况在内部是一致的,并且typechecker爱你。
在一个列表中理解, x <- ys
结合x
在每个元件ys
。 基本上,你正试图改变:
[ f foo | foo <- bar ]
成
[ f bar ]
词组
y <- perms (takeOut i xs)
意味着“对于takeOut i xs
每个排列y
”。 所以[ x:y | ... ]
[ x:y | ... ]
为每个排列预先设置x
。
相应地,这句话
y <- takeOut i xs
表示“对于takeOut i xs
每个元素y
”。 所以[ x:perms y | ... ]
[ x:perms y | ... ]
试图找到元素 y
所有排列(甚至不是列表),然后将x
到排列列表中。 某些东西的排列是一个列表列表,因此x
必须是一个列表来执行此操作,而不是。 所以,基本上,第二个没有意义。
我明白为什么你会被抛弃。 请记住, <-
与let
,它意味着每一个 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.