簡體   English   中英

Haskell從另一個函數檢查函數的返回類型

[英]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)

通常, sequencemap這種組合稱為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.

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