我正在尝试在Haskell中为Brainf * ck编写一个解释器。但是我收到了类型错误。
只有代码的相关部分如下所示:
--my own defined data type
data BFState = BFState {
program :: String, -- program being interpreted
input :: String, -- input for the program
memory :: [Word8], -- memory is a list of 8bit representation of INTs since only least 8 bits are read
prog_pointer :: Int, -- current pointer in the program STRING (pc)
mem_pointer :: Int -- current pointer in the memory LIST (pos)
}
--Initialise the BFState before the Intepreter runs the inputted BF code.
initState :: String -> String -> Int -> BFState
initState program input memSize = BFState program input (take memSize (repeat 0)) 0 0
--Helper function for the main function (bf program input)
run state = if isEnd state
then return () --when reached the end, just return
else do newState <- (iterateBF state) --update to new state after iterating one BF comand
run newState --run with new state
--the main function
bf program input = run (initState program input 10000)
现在,我收到类型错误:
Couldn't match expected type `String'
with actual type `BFState -> String'
In the first argument of `initState', namely `program'
In the first argument of `run', namely
`(initState program input 10000)'
In the expression: run (initState program input 10000)
编译器在说actual type 'BFState -> String'
时指的是什么?
----对于sepp2k
iterateBF :: BFState -> IO BFState
iterateBF state = case (program state !! prog_pointer state) of
'+' -> return state {memory = setMem state ((getMem state) + 1), prog_pointer = nextPP state}
'-' -> return state {memory = setMem state ((getMem state) - 1), prog_pointer = nextPP state}
'>' -> return state {mem_pointer = (mem_pointer state) + 1, prog_pointer = nextPP state}
'<' -> return state {mem_pointer = (mem_pointer state) - 1, prog_pointer = nextPP state}
'[' -> return state {prog_pointer = prog_pointer'} where
prog_pointer' = findClosingBrace (program state) (prog_pointer state)
']' -> return state {prog_pointer = prog_pointer'} where
prog_pointer' = findOpeningBrace (program state) (prog_pointer state)
',' -> let inputVal = fromIntegral (fromEnum (head (input state))) in
return state {memory = setMem state inputVal, prog_pointer = nextPP state, input = drop 1 (input state)}
'.' -> do hPutChar stdout (chr (fromEnum $ getMem state))
hFlush stdout
return state { prog_pointer = prog_pointer state}
otherwise -> return (state {prog_pointer = nextPP state}) --ignore other characters
--check if we are at the end of the program
isEnd :: BFState -> Bool
isEnd state = (prog_pointer state) >= length (program state)
答案 0 :(得分:4)
那是因为“program”的类型(initState函数的第一个参数)不是String。它实际上是BFState - &gt;字符串,您可以通过在ghci提示符下键入“:t program”来验证(当然没有引号)。
答案 1 :(得分:1)
program
预期的类型为String
(因为initState
的类型签名应该是这样),但实际< / em>的类型为BFState -> String
,因为这是bf
的第一个参数的类型。
如果为bf
提供显式类型签名,您可能会发现代码中的实际错误是您使用bf
类型的第一个参数调用BFState -> String
的某个地方