簡體   English   中英

Haskell IO功能類型不匹配

[英]Haskell IO function type mismatch

以下代碼有什么問題:

nextMatch :: (a -> Bool) -> [IO a] -> (IO a, [IO a])
nextMatch f (x:xs) = do
    s <- x
    if f s then (return x, xs)
        else nextMatch f xs

編譯錯誤說:

src\Main.hs:364:10:
    Couldn't match expected type `(IO a, t0)' with actual type `IO a'
    In a stmt of a 'do' block: s <- x
    In the expression:
      do { s <- x;
           if f s then (return x, xs) else nextMatch f xs }
    In an equation for `nextMatch':
        nextMatch f (x : xs)
          = do { s <- x;
                 if f s then (return x, xs) else nextMatch f xs }

我想要一個函數,該函數在列表中搜索匹配項,然后將匹配的元素加上其余列表作為元組返回。

我對Haskell還是很陌生,所以這個問題可能很簡單...

謝謝! 克里斯

您不需要在這里處理IO 這就是我將其實現為純函數的方式(我添加了Maybe類型,因為可能沒有下一個匹配項):

nextMatch :: (a -> Bool) -> [a] -> Maybe (a, [a])
nextMatch _ []     = Nothing
nextMatch f (x:xs) = if f x then Just (x, xs) else nextMatch f xs

作為初學者,如果您將IO用作函數的輸入,或者要返回其中包含IO的數據結構,則可能是您做錯了一些事情(可能是您想要的代碼)從此調用)。

由於x if類型為IO a ,因此無需將其返回,這與肯定需要注入monad的元組相反。

if f s then return $ (x, xs)

但是,這不是唯一的問題,因為您進入了IO monad,並且您的簽名沒有反映出來,因為您返回的類型是(IO a, [IO a])所以應該是IO (IO a, [IO a]) 然后,您的代碼應如下所示。

nextMatch :: (a -> Bool) -> [IO a] -> IO (IO a, [IO a])
nextMatch f (x:xs) =  
  do 
    done <- fmap f x  
    if done
    then return $ (x, xs)
    else nextMatch f xs 

無論如何,我不知道您要做什么,但是函數的簽名看起來很尷尬。 它看起來應該更像nextMatch :: (a -> Bool) -> [a] -> (a, [a]) ,然后使用return即可構建它的monadic版本。 nextMatchIO = return $ nextMatch ,然后使用Control.Monad提供的其他函數將此計算插入到您的控制流中。

您的函數應該返回一個元組。 如果我的Haskell仍然達到標准,我將嘗試在返回函數“ if fs then(return(x,xs))”周圍放置parens。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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