[英]Haskell checking return type of function from another function
我有一個Haskell代碼,它有兩個函數:
第一個功能:
functionA :: [Int] -> Maybe Int
第二個:
functionB :: Int -> Maybe Int
我想要做的是遞歸[Int]的每個元素並將其提供給functionB。 如果函數B返回一個Int,那么移動到下一個元素,如果它返回Nothing,那么functionA也不返回任何內容。
知道如何最好地做到這一點?
謝謝 :)
您可以使用sequence
將[Maybe Int]
帶到Maybe [Int]
functionA ints = sequence (map functionB ints)
通常, sequence
和map
這種組合稱為mapM
。
functionA ints = mapM functionB ints
你的問題有一些不清楚的事情因此我做了一些假設。 functionA
就像折疊一樣,它將[Int]
轉換為Maybe Int
但在折疊整數之前它調用functionB
將每個整數轉換為Maybe Int
,其中Nothing
結果表明轉換失敗,導致functionA
失敗並使其失效Nothing
。
import Control.Applicative
functionA :: [Int] -> Maybe Int
functionA nums = foldl (\x y -> (+) <$> x <*> y) (Just 0) $ map functionB nums
functionB :: Int -> Maybe Int
functionB 2 = Nothing
functionB x = Just (x+x)
在上面的示例中, +
用於折疊操作,而functionB
在編號2上失敗
J. Abrahamson回答說得對,但他將結果函數命名為異常並且讓你感到困惑。
我們有一下:
ints :: [a]
functionA :: [a] -> Maybe a
functionB :: a -> Maybe a
所以我們希望得到地圖functionB
:
functionC :: a -> Maybe [a]
functionC ints = mapM functionB ints
但是functionC
結果類型是Maybe [a]
,而不是[a]
,所以我們使用fmap
result :: [a] -> Maybe a
result ints = join $ fmap functionA $ functionC ints
我們還使用join
來擺脫Maybe (Maybe a)
結果
或者讓我們寫一行:
result :: [a] -> Maybe a
result = join . fmap functionA . mapM functionB
更新
但在此解決方案中始終計算所有的ints
。 如果我們想停止計算,我們需要有mapIfAllJust
函數,如下所示:
result :: [a] -> Maybe a
result = join . fmap functionA . sequence . mapIfAllJust functionB
mapIfAllJust :: (a -> Maybe b) -> [a] -> [Maybe b]
mapIfAllJust _ [] = []
mapIfAllJust f (x:xs) = go f (f x) [] xs
where
go _ Nothing _ _ = [Nothing]
go _ pr used [] = pr : used
go f pr used (nxt:rst) = go f (f nxt) (pr : used) rst
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.