Search code examples
haskellinfix-notation

Rewrite a monad computation in prefix notation


I'm trying to figure out how to rewrite a monadic computation with prefix notation (not for real practical goals, just for research), but the problem that one lambda doesn't see another one's parameter

so given a working example

*Main> [1, 3, 4] >>= \x -> [x + 1, x - 1] >>= \y -> return (y*x)
[2,0,12,6,20,12]

the rewritten one shows the error on not seeing the parameter of other lambda

*Main> (>>=) ( (>>=)  [1, 3, 4] (\x -> [x + 1, x - 1]) ) (\y -> return (y*x))
<interactive>:133:68: Not in scope: `x'

but if I make the last one not using it (by replacing x with y), the computation starts working

*Main> (>>=) ( (>>=)  [1, 3, 4] (\x -> [x + 1, x - 1]) ) (\y -> return (y*y))
[4,0,16,4,25,9]

So does full rewriting in prefix notation technically possible? Or this property of accessing other lambdas parameters is exclusive to the infix notation?


Solution

  • The problem is that you got the precedences slightly wrong, see also Haskell Precedence: Lambda and operator

    The body of a lambda-expression extends as far to the right as possible. Then your example is parenthesized as follows:

    [1, 3, 4] >>= (\x -> [x + 1, x - 1] >>= (\y -> return (y*x)))
    

    Bringing it into prefix form results in

    (>>=) [1, 3, 4] (\x -> (>>=) [x + 1, x - 1] (\y -> return (y*x)))
    

    Now x is visible inside the body of \y -> ....