过滤器和filterM都不-Bool与IO Bool的区别

rns*_*nso 1 haskell filter

我正在尝试筛选出包含斜杠的那些字符串:

import Data.List
import Control.Monad(filterM)

hasSlash :: [Char] -> Bool
hasSlash firline = do
    isInfixOf "/" firline

main :: IO ()
main = do
    let d = ["abcd","abc/d","a/bcd","abcd","ab/cd"]
    -- filter out those that do not have '/'
    e <- filterM hasSlash d
    print e
Run Code Online (Sandbox Code Playgroud)

但是,我得到以下错误:

soq_filter.hs:13:18: error:
    • Couldn't match type ‘Bool’ with ‘IO Bool’
      Expected type: [Char] -> IO Bool
        Actual type: [Char] -> Bool
    • In the first argument of ‘filterM’, namely ‘hasSlash’
      In a stmt of a 'do' block: e <- filterM hasSlash d
      In the expression:
        do { let d = ...;
             e <- filterM hasSlash d;
             print e }
Run Code Online (Sandbox Code Playgroud)

问题在哪里,如何解决?谢谢。

Jos*_*ica 5

您不需要,不需要或IO任何其他monad进行该过滤。改为这样做:

import Data.List

hasSlash :: [Char] -> Bool
hasSlash firline = isInfixOf "/" firline

main :: IO ()
main = do
    let d = ["abcd","abc/d","a/bcd","abcd","ab/cd"]
    -- filter out those that do not have '/'
    let e = filter hasSlash d
    print e
Run Code Online (Sandbox Code Playgroud)

请注意使用let e =代替e <-以避免需要单子上下文。