reset password
Author Message
rabbott
Posts: 1649
Posted 13:57 Apr 05, 2019 |

For the RPN problem (B.ii) you will need a Python version of foldM. I had a difficult time finding a Haskell version. But here's one from the Haskell wiki page on Monads.

foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldM f a []     = return a  -- Recall that "return" wraps its argument.
foldM f a (x:xs) = f a x >>= \y -> foldM f y xs

After looking at it, you should be able to translate it into Python using PyMonad notation.  My version is almost a direct translation and looks like this.

def foldM(f: Callable[[T1, T2], Monad], acc: T1, xs: List[T2]) -> Monad:
    if not(xs):
        return Just(acc)
    return f(acc, xs[0]) >>   <a lambda expression that makes a recursive call to foldM>

You figure out the lambda expression. 

The lambda expression has one argument, which is the unwrapped result of f(acc, xs[0]). (Recall that >> unwraps results when it passes them on.)

Last edited by rabbott at 15:03 Apr 05, 2019.