我正在尝试过滤掉那些包含斜杠的字符串:
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
但是,我得到了以下错误:
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 }
问题在哪里?如何解决?谢谢。
发布于 2019-09-15 17:55:33
您不需要也不想要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
请注意,为了避免需要一元上下文,使用了let e =
而不是e <-
。
https://stackoverflow.com/questions/57946743
复制