我試圖在我的函式中填充一個由兩個串列組成的元組,并且根據條件,我希望每個元組都填充一個不同的串列。代碼如下:
type One = []
type Two = []
bar :: Int -> Bool
bar ...
foo :: Somelist -> (One, Two)
foo somelist
| null somelist = ([],[])
| bar yesno = {-I want to fill the list "One" here if bar == true-} foo (tail somelist)
| otherwise = {-and the list "Two" here if bar == false-} foo (tail somelist)
什么是解決這個問題的優雅和 Haskelly 方法:)?
謝謝你的建議。
uj5u.com熱心網友回復:
與您的示例相比,我對型別進行了一些更改,以使代碼可測驗。
type One = [Integer]
type Two = [Integer]
bar :: Integer -> Bool
bar x = x > 0
foo :: [Integer] -> (One, Two)
foo [] = ([], [])
foo (x:xs)
| bar x = (x:one, two)
| otherwise = (one, x:two) where
(one, two) = foo xs
快速測驗:
λ> foo [-10..10]
([1,2,3,4,5,6,7,8,9,10],[-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0])
這個想法是向下遞回到串列的末尾并回傳一個串列元組,然后當你進入遞回堆疊時,從下面的函式中獲取回傳的元組并將當前元素的值添加到基于你的謂詞。
或者您可以將partitionfromData.List與 type 一起使用partition :: (a -> Bool) -> [a] -> ([a], [a])。這個函式接受一個串列和一個謂詞,并回傳一個由 2 個串列組成的元組:一個是謂詞回傳 true,另一個是它回傳 false。
import Data.List (partition)
foo2 :: [Integer] -> (One, Two)
foo2 xs = partition bar xs
您可以 eta 減少上述內容,但為了清楚起見,我沒有這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/340904.html
