gpt4 book ai didi

haskell - 使用 Haskeline 的 getInputLine 的输入

转载 作者:行者123 更新时间:2023-12-02 16:46:43 24 4
gpt4 key购买 nike

我有代码

 main :: IO()
main = runInputT defaultSettings loop
where
--loop :: InputT IO ()
loop = do
minput <- getInputLine "$ "
case minput of
Nothing -> return ()
Just input -> process $ words input
loop

流程具有类型定义的位置

process :: [String] -> IO ()

但是我收到错误:

• Couldn't match type ‘IO’ with ‘InputT m’                                                       
Expected type: InputT m ()
Actual type: IO ()
• In the expression: process $ words input
In a case alternative: Just input -> process $ words input
In a stmt of a 'do' block:
case minput of {
Nothing -> return ()
Just input -> process $ words input }

我想知道是否有人可以解释我做错了什么。我只想从 getInputLine 获取原始输入来执行其他操作。

谢谢

最佳答案

do 中的所有语句block 必须具有相同的类型(嗯,其类型中必须具有相同的 monad)。在您的情况下,这是 InputT IO something (单子(monad)是 InputT IO )。

getInputLine "$ "类型为InputT IO (Maybe String) ,所以这部分没问题。

然后你就有了 case表达式,这意味着所有分支需要具有相同的类型。第一个分支只是 return () ,其类型为 InputT IO () 。到目前为止一切都很好。

第二个分支是 process $ words input 。但这有类型 IO () ,不是InputT IO () ,这是编译器此时所期望的。

要解决这个问题:幸运的是,有一种简单的方法可以转换(“提升”) IO x 类型的值。至InputT IO x ,即 liftIO功能:

Just input -> liftIO (process $ words input)

liftIO :: IO a -> InputT IO a (实际上它比这更通用: liftIO :: (MonadIO m) => IO a -> m a 但这在这里并不重要)。

关于haskell - 使用 Haskeline 的 getInputLine 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com