我讀Dynamic programming example,有這樣的代碼:警衛在哈斯克爾
buy n = r!n
where r = listArray (0,n) (Just (0,0,0) : map f [1..n])
f i = do (x,y,z) <- attempt (i-6)
return (x+1,y,z)
`mplus`
do (x,y,z) <- attempt (i-9)
return (x,y+1,z)
`mplus`
do (x,y,z) <- attempt (i-20)
return (x,y,z+1)
attempt x = guard (x>=0) >> r!x
我的問題是如何attempt x = guard (x>=0) >> r!x
作品?
根據該Control.Monad源代碼,
guard True = pure()
guard False = empty
pure :: a -> f a
m >> k = m >>= \_ -> k
所以如果x> 0,則:
attempt x
= (guard True) >> (r!x) = (pure()) >> (r!x)
= (pure()) >>= \_ -> r!x = (f()) >>= (\_ -> r!x)
因此f()
應(在這種情況下Maybe a
)是m a
類型,但如何做Haskell知道什麼f
是?因爲它從未被指定,所以f()
可以返回empty
。 (f
f
指在純)
如果x < 0,empty
不在Maybe
,如何能這仍然施加到>>=
?
'純()::也許(==剛()'? – Mephy
@Mephy'Maybe()== Just()'如何應用於'>> ='? – CYC
在[this source](http://hackage.haskell.org/package/base-4.8)的第634行中沒有應用程序,'pure():: Maybe()'被定義爲'Just() .1.0 /文檔/ SRC/GHC.Base.html)。 – Mephy