将monadic函数传递给期望正常函数的位置

时间:2014-03-01 16:03:40

标签: haskell

如果我有一个功能

pretty :: FilePath -> IO String

如何将其传递给

interact :: (String -> String) -> IO ()

1 个答案:

答案 0 :(得分:7)

首先,interact :: (String -> String) -> IO (),请注意括号。这是一种完全不同的类型。

书写

main = interact f

is the same as writing

main = do s <- getContents
          putStr (f s)

现在,getContents :: IO String,即与pretty filename相同的类型,filename :: FilePath。所以人们可以而不是另一个:

myinteraction filename f = 
    do
       s <- pretty filename
       putStr (f s)

但你不能强迫它不适合。