假設我想做類似的事情"ace" `elem` "abcdefg"。當然我們不能,因為您需要第一個元素型別的串列。相反,有沒有一種方法可以將其轉換為獲取“ace”中的每個字符并將它們單獨與“abcdefg”進行比較,然后使用 or 陳述句來組合它們,但無需手動執行此操作(因為在我的程式中它是一個未知長度的變數和字符)。
uj5u.com熱心網友回復:
這是一個更普遍問題的特定情況:您有一個函式Char -> Bool(或a -> Bool)并且您想將它改編為一個函式[a] -> Bool。換句話說,你需要的是一個函式
adaptOr :: (a -> Bool) -> ([a] -> Bool)
嗯,這實際上是你可以問 Hoogle 的事情!第一個命中是
any :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, any determines if any element of the list satisfies the predicate. For the result to be False, the list must be finite; True, however, results from a True value for the predicate applied to an element at a finite index of a finite or infinite list.
>>> any (> 3) []
False
>>> any (> 3) [1,2]
False
>>> any (> 3) [1,2,3,4,5]
True
>>> any (> 3) [1..]
True
>>> any (> 3) [0, -1..]
* Hangs forever *
all :: (a -> Bool) -> [a] -> Bool
base GHC.List GHC.OldList
Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate. For the result to be True, the list must be finite; False, however, results from a False value for the predicate applied to an element at a finite index of a finite or infinite list.
>>> all (> 3) []
True
>>> all (> 3) [1,2]
False
>>> all (> 3) [1,2,3,4,5]
False
>>> all (> 3) [1..]
False
>>> all (> 3) [4..]
* Hangs forever *
現在您需要考慮哪些適合您的情況,然后相應地使用它。你要
all?any (\c -> c`elem`"abcdefg") "ace"
這也可以用中綴部分撰寫:
all?any (`elem`"abcdefg") "ace"
uj5u.com熱心網友回復:
or這是您想要的使用該陳述句:
or [c `elem` "abcdefg" | c <- "ace"]
如何想出這個?
你已經知道你想要
'a' `elem` "abcdefg" ||
'c' `elem` "abcdefg" ||
'e' `elem` "abcdefg"
的型別(||)是Bool -> Bool -> Bool。
但是你有一個要測驗的字符串列。在您測驗了它們中的每一個之后,您將獲得布爾結果串列。因此,您需要 type 的函式[Bool] -> Bool。
胡歌時間!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427268.html
標籤:哈斯克尔
