使用IO()操作,但返回IO X.

时间:2016-04-21 16:59:43

标签: haskell io monads

我有一个返回IO X的函数(假设X是特定类型)。其中一个参数是输出目录的路径。如果这不存在,则必须创建它。

我想使用返回IO()的createDirectoryIfMissing,但我不知道如何保持类型一致。我所做的(并且失败了)是这样的:

process :: (Mutation a, Show a, Arbitrary a)
=> ((a -> BSL.ByteString),(BS.ByteString -> a))
-> Bool -> FilePath -> String -> String ->
Int -> Int -> FilePath -> FilePath -> IO Result 
process (mencode,mdecode) par filename cmd prop maxSuccess maxSize outdir seeds =  
let (prog, args) = (Prelude.head spl, Prelude.tail spl)
in (case prop of
    "exec" ->
        quickCheckWithResult stdArgs { maxSuccess = maxSuccess , maxSize = maxSize, chatty = not par }
        (noShrinking $ execprop filename prog args mencode outdir)
    "honggfuzz" ->
        --do
        --createDirectoryIfMissing True outdir (This fails)
        quickCheckWithResult stdArgs { maxSuccess = maxSuccess , maxSize = maxSize, chatty = not par }
        (noShrinking $ honggprop filename prog args mencode outdir)

    _     -> process_custom arbitrary (mencode,mdecode) par filename cmd prop maxSuccess maxSize outdir seeds

) where spl = splitOn " " cmd

quickCheckWithResult :: Testable prop => Args - >道具 - > IO结果 process_custom与process基本相同,但使用另一个参数

编辑:现在的实际代码,抱歉

1 个答案:

答案 0 :(得分:2)

示例:

foo :: Int -> IO Int
foo n = do
   putStrLn "Hello"   -- :: IO ()
   return (n+1)       -- :: IO Int

do块中的最后一个语句必须与函数签名匹配。

或者,使用>>>>=

foo n = putStrLn "Hello" >> return (n+1)
bar n = getChar >>= \c -> return (fromEnum c)

都有Int -> IO Int类型。