Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

One can use it to solve homework problems.

A problem I gave my class last week: you are holding 4 cards, 9, 10,k,Q. You draw the 5'th card from the deck, and if you don't like it, you can discard it and draw another. Obviously, you want a Jack, to get an inside straight.

The probability monad lets you describe your choices "imperatively" using monads and do notation. I.e., if I draw a Jack, keep it (I have a straight), otherwise draw again.

Note: I'm assuming below that cards with index 1,2,3,4 are jacks,

    import Probability
    import Collection
    import Prelude
    import Monad

    insideStraight deck tries= do (card, rem) <- (selectOne deck)
                                  let straight = if (card < 4) then True else False in
                                      if (tries == 1 || straight)
                                          then return straight --If I got a straight, return True. If I have no tries left, return False.
                                          else insideStraight rem1 (tries - 1) --If I can try again, and I don't have a straight, do so.

    main =  do putStrLn "With no discards:"
               putStrLn (show (insideStraight [1 .. 48] 1))
               putStrLn "With one card discarded: "
               putStrLn (show (insideStraight [1 .. 48] 2))


I don't read Haskell, and though I tried searching for it, I was unsuccessful, so I figured I'd ask.

What's the "(card, rem) <- (selectOne deck)" notation mean? And does the "in" put the second if statement inside the else clause of the first if statement, or outside of it?

Thanks


The notation x <- f y means "f y returns a monadic value; take the next line (which is a monadic function) and apply it to x."

Naively, you can think of x <- f y as pulling the value out of the monad. Now you can apply non-monadic functions to it. In a certain sense, this is true. However, by the time the do statement is finished, you will need to push it back in (the return statement). So you can only pull stuff out of the monad if you immediately put it back in (otherwise you get a type error).

(card, rem) is simply unpacking a 2-tuple, containing the card and the remaining deck (after picking 1 element).

The "let straight = ... in \newline (some statement)" means exactly what it sounds like. "let x = 3 in xx" means "take the statement xx, replace x by 3, you get 3*3=9".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: