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

Saw*_*yer 2 haskell

如果我有一个功能

pretty :: FilePath -> IO String
Run Code Online (Sandbox Code Playgroud)

我怎么能把它传递给

interact :: (String -> String) -> IO ()
Run Code Online (Sandbox Code Playgroud)

Wil*_*ess 7

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

写作

main = interact f
Run Code Online (Sandbox Code Playgroud)

和写作一样

main = do s <- getContents
          putStr (f s)
Run Code Online (Sandbox Code Playgroud)

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

myinteraction filename f = 
    do
       s <- pretty filename
       putStr (f s)
Run Code Online (Sandbox Code Playgroud)

但你不能只在不适合的地方强迫它.