我正在尝试在 Haskell中实现海龟图形。目标是能够编写这样的函数:
draw_something = do
forward 100
right 90
forward 100
...
然后让它产生一个点列表(可能带有其他属性):
> draw_something (0,0) 0 -- start at (0,0) facing east (0 degrees)
[(0,0), (0,100), (-100,100), ...]
我所有这些都以“正常”的方式工作,但我未能将其实现为 Haskell Monad 并使用 do-notation。基本代码:
data State a = State (a, a) a -- (x,y), angle
deriving (Show, Eq)
initstate :: State Float
initstate = State (0.0,0.0) 0.0
-- constrain angles to 0 to 2*pi
fmod :: Float -> Float
fmod a
| a >= 2*pi = fmod (a-2*pi)
| a < 0 = fmod (a+2*pi)
| otherwise = a
forward :: Float -> State Float -> [State Float]
forward d (State (x,y) angle) = [State (x + d * (sin angle), y + d * (cos angle)) angle]
right :: Float -> State Float -> [State Float]
right d (State pos angle) = [State pos (fmod (angle+d))]
bind :: [State a] -> (State a -> [State a]) -> [State a]
bind xs f = xs ++ (f (head $ reverse xs))
ret :: State a -> [State a]
ret x = [x]
有了这个我现在可以写
> [initstate] `bind` (forward 100) `bind` (right (pi/2)) `bind` (forward 100)
[State (0.0,0.0) 0.0,State (0.0,100.0) 0.0,State (0.0,100.0) 1.5707964,State (100.0,99.99999) 1.5707964]
并得到预期的结果。但是我不能将此作为Monad
.
instance Monad [State] where
...
结果是
`State' is not applied to enough type arguments
Expected kind `*', but `State' has kind `* -> *'
In the instance declaration for `Monad [State]'
如果我将列表包装在一个新对象中
data StateList a = StateList [State a]
instance Monad StateList where
return x = StateList [x]
我明白了
Couldn't match type `a' with `State a'
`a' is a rigid type variable bound by
the type signature for return :: a -> StateList a
at logo.hs:38:9
In the expression: x
In the first argument of `StateList', namely `[x]'
In the expression: StateList [x]
我尝试了各种其他版本,但我从来没有让它像我想的那样运行。我究竟做错了什么?我怎么理解不正确?