![](/img/trans.png)
[英]How do I find an element in an infinite list using the foldr function in Haskell?
[英]How do I compare a given variable list with an infinite list to find the first non-occurring variable in Haskell?
希望對我的新手 Haskell 代碼有所幫助。
我正在嘗試將變量的輸入列表與無限的變量列表進行比較
input = ["a", "b", "x"]
variables = ["a", "b", "c", "d", ... "a1", "b1", ... and so on]
我想在輸入列表中找到第一個不出現的變量,在這種情況下它應該是“c”。
我認為 go 關於它的正確方法是使用過濾器......
ourFilter :: [Var] -> [Var] -> [Var]
ourFilter p [] = []
ourFilter p (x:xs) | matches x = x ourFilter xs
| otherwise = ourFilter xs
matches :: Var -> Bool
matches n = n `elem` variables
...但是我在編譯之前遇到了兩個錯誤,我無法理解它們:
• Couldn't match expected type ‘([Var] -> [Var] -> [Var])
-> [Var] -> [Var]’
with actual type ‘[Char]’
• The function ‘x’ is applied to two arguments,
but its type ‘[Char]’ has none
有人可以幫助解釋到底發生了什么嗎? 這是 go 的正確方法嗎?
謝謝!
你忘記了一個冒號:
... = x : ourFilter xs
^
您還需要在每次遞歸調用時再次傳遞p
:
... | matches x = x : ourFilter p xs | otherwise = ourFilter p xs
^ ^
還有其他問題(例如,實際上從未使用過p
的事實似乎是一個危險信號),但這將使它編譯,以便您可以使用它並自己修復它們。
您應該枚舉無限列表,並為每個項目檢查它是否是列表的成員。 如果不是這種情況,則返回該值; 否則在列表的尾部遞歸。 因此,這看起來像:
ourFilter :: [Var] -> [Var] -> Var
ourFilter input = go
where go (x:xs)
| x `elem` input = … -- (1)
| otherwise = … -- (2)
我離開時填寫…
部分作為練習。 對於(1),您使用列表的尾部對go
進行遞歸; 對於(2),您返回變量,因為這是第一個不發生的變量。
可以將此 function 轉換為使用foldr
的 function:
ourFilter :: [Var] -> [Var] -> Var
ourFilter input = foldr f undefined
where f x y | x `elem` input = … -- (1)
| otherwise = … -- (2)
這里y
是對列表尾部進行遞歸調用的結果。
列表差\\
可以從一個無限列表中減去一個有限列表:
> import Data.List
> head $ [1..] \\ [1,2,3,5,7,9]
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.