简体   繁体   中英

Decision Tree in haskell defining >>= and return

I'm trying to make a Decision Tree for a game and I have:

data DecisionTree a
   = Result a
   | Decision [DecisionTree a]
   deriving (Eq,Show)`

furthermore, I have

instance Functor DecisionTree where
    fmap = liftM

now I have to define

instance Monad DecisionTree where
-- return :: a -> DecisionTree a
   return = ...
-- (>>=) :: DecisionTree a -> (a -> DecisionTree b) -> DecisionTree b
   (>>=) = ...

Now I'm kinda confused how to fill in the definitions.

To define >>= I tried splitting the definition into two cases:

(>>=) (Result a) f    = f a
(>>=) (Decision ys) f = Decision (fmap (>>= f) ys)

As for return I thought at least something like

return = Result

but this only builds Result a and no Decision [DecisionTree a] .

Am I completely off or am I close?

This is the free monad for [] . As such, while there may be multiple ways to define a monad instance (per @leftroundabout), there is one canonical way to define a free monad instance, which is the one you have chosen. (You can compare your implementation to that of Free and see that they are equivalent. The only difference is that you fix the choice of f to [] .)

but this only builds Result a and no Decision [DecisionTree a] .

I'm not sure what this means, but an arrow a -> DecisionTree b that produces a Decision will produce a Decision . return will always produce a Result , but that is expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM