2

How can this code (or in general, code with multiple inputs) can be reduced/simplified?

do
  sex    <- askSex
  name   <- askName
  sayHello sex name

In this case is very short already, but when it gets to multiple inputs, it looks messy. Is there any way to do something like:

sayHello askSex askName

?

5
  • 1
    This code looks perfectly simple to me Jan 9, 2013 at 17:50
  • 2
    Everything shorter than this will most likely be bizarre. If you were asking for a lot of the same kind of inputs, you might map over those actions, but not in this case.
    – Sarah
    Jan 9, 2013 at 17:51
  • 5
    Check out the functions in Control.Monad, specifically liftM2.
    – sabauma
    Jan 9, 2013 at 17:56
  • 2
    As sabauma says, use liftM2. It's an abstraction of your original code and just what you want.
    – Fixnum
    Jan 9, 2013 at 17:56
  • n.b. It is clearer if you include the do from the start of the do-block.
    – dave4420
    Jan 9, 2013 at 18:01

3 Answers 3

5

If you

import Control.Applicative  -- for <$> and <*>
import Control.Monad        -- for join

you can write

join $ sayHello <$> askSex <*> askName

For your example, where you are only fetching two parameters, this is not a big win. But for a greater number of parameters it can make the code clearer.

join $ doSomething <$> getFirst <*> getSecond <*> getThird <*> getForth
2
  • 1
    It's a shame idiom brackets haven't made it into Haskell: join (|doSomething getFirst getSecond getThird getForth|) would be much nicer.
    – dave4420
    Jan 9, 2013 at 18:12
  • Well, there's always the quasiquoter Jan 9, 2013 at 23:59
3

This is a lovely time for Applicative Functors:

import Control.Applicative -- at the top of your module before any functions

hello "Male" name = "Hi, " ++ name ++ ", that's a cool name."
hello "Female" name = "Hello, " ++ name ++ ", that's a pretty name."

greet = hello <$> askSex <*> askName >>= putStrLn

It works a bit like fmap in the previous answers I gave you today, but for larger numbers of arguments, like you have here.

Using functions like my hello with applicative functors helps you separate your IO code from the rest of the code, which is very good practice. Try to write hello instead of sayHello every time.

1

Annoyingly, hoogle doesn't have an easy answer for this one. This would be called bind2. If it's a function with only one input, then you can use =<<, the infix version of what I'd call bind1.

sayHello =<< askName

But for multiple inputs, we're out of luck. For whatever reason, the standard libs don't provide this:

bind2 :: Monad m => (a -> b -> m c) -> m a -> m b -> m c
bind2 f mx my = do
  x <- mx
  y <- my
  f x y

...

bind2 sayHello askSex askName

You can, of course, just define it yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.