簡體   English   中英

Haskell中的“無法創建無限類型”錯誤

[英]“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 :: ay :: [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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM