I'm trying to understand Haskell monads and wrote this test program, which compiles and works as expected:
divide :: Int -> Int -> Either String Int
divide _ 0 = Left "Divide by zero error
divide numerator denom = Right (numerator `div` denom)
processNumsMonadically :: Int -> Int -> Either String Int
processNumsMonadically n d = divide n d >>= \q -> return (q+1)
When I try using the word bind instead of the >>= operator in the latter function definition:
processNumsMonadically n d = bind (divide n d) (\q -> return (q+1))
I get the error:
Not in scope: 'bind'
What is the correct way to use the word bind?
1 Answer 1
This isn't a part of Prelude; it resides in Control.Monad.Extra, a part of monad-extras package.
However, you can call operators in prefix manner (like named functions) easily:
processNumsMonadically n d = (>>=) (divide n d) (\q -> return (q+1))
You could also just use do notation:
processNumsMonadically n d = do
q <- divide n d
return (q+1)
But while we're at it, I'd write using a Functor:
processNumsMonadically n d = fmap (+1) (divide n d)
or Applicative syntax:
processNumsMonadically n d = (+1) <$> divide n d
You could also lift the +1 to avoid the need for return and the lambda.
As a personal style remark, bind used as a word isn't idiomatic, and IMHO you shouldn't use it.
3 Comments
bind as a word in programs, just as an intermediate step when teaching monads. I appreciate the do syntax.
bindis not a keyword. It's a name people use to refer to>>=operator. You can definebind = (>>=)if that helps.class,instance,type,newtype,data,case'of,do,if'then'else,let'in,where: those are pretty much all that can occur in the actual code part. Plus a few more which are only used in the module header, and a few from GHC extensions – the full list is here.) All other words are simply names of functions/actions, defined in some library (if not in your own code); you can use Hoogle or Hayoo to find them.