作为练习,我正在Haskell中编写一个命令行RPN计算器。其思想是,它将提示输入(一个数字或运算符)并打印出新的堆栈。我的计划是将数字列表存储在状态单元中,并对该列表执行计算。例如:
> 4
[4]
> 3
[3,2]
> 5
[5,3,2]
> +
[8, 2]诸若此类。
首先,我尝试在State中建立一个列表,每个条目上都有输入和输出。由于IO和State在同一个函数中的组合,我已经被困住了。我的问题是,我还需要递归输入,以保持提示符后的第一个数字是输入。
到目前为止,我的代码如下:
module Main where
import Control.Monad.State
addEntry :: Int -> State [Int] Int
addEntry entry = do
entries <- get
put (entry : entries)
return entry
mainLoop :: [Int] -> IO ()
mainLoop entries = do
entry <- readLn
newEntries <- execState (addEntry entry) entries
print newEntries
mainLoop newEntries
main :: IO ()
main = do
print $ mainLoop []下面是我当前遇到的编译器错误:
src/Main.hs@14:28-14:42 Couldn't match type [Int] with ‘IO [Int]’
Expected type: State (IO [Int]) Int
Actual type: State [Int] Int …
src/Main.hs@14:44-14:51 Couldn't match expected type ‘IO [Int]’ with actual type [Int] …关于如何构造这些函数,我没有将IO和State结合在一起,有什么建议吗?
发布于 2014-10-01 15:47:32
我不确定您是否使用了state,因为您想尝试一下,但是您可以实现状态本身而不需要状态单点的“麻烦”。
module Main where
addEntry :: Int -> [Int] -> [Int]
addEntry = (:)
mainLoop :: [Int] -> IO ()
mainLoop entries = do
entry <- readLn
let newEntries = addEntry entry entries
print newEntries
mainLoop newEntries
main :: IO ()
main = mainLoop []https://stackoverflow.com/questions/26144119
复制相似问题