2

I noticed some function names ending with _ in Haskell (e.g. mapM_, traverse_).

What does it mean?

  • 2
    Do you mean like traverse_, mapM_, etc.? – bradrn Apr 18 at 7:20
  • 4
    It's briefly mentioned under "naming conventions" here: hackage.haskell.org/package/base-4.12.0.0/docs/… Essentially it's used to mean that the "result" of a monadic value/action is ignored, the action being used purely for its "side effects". (Quotes are because this is strictly true only for IO, where I think the distinction is easier to understand - for other, "pure" Monads/Applicatives, it's more of an analogy.) – Robin Zigmond Apr 18 at 7:27
  • 2
    @RobinZigmond I wouldn't call it an analogy, so much as a generalization. It means "for its Applicative effects", where for IO that effect is often called a side effect. – amalloy Apr 18 at 8:03
12

It's just a naming convention in the Prelude. Generally, the functions without an underscore (e.g. traverse, sequence, mapM) return some meaningful 'aggregate' value, whereas the counterparts with an underscore (e.g. traverse_, sequence_, mapM_) return (). Usually you would use the first set of functions, but if you don't care about the return value then you would use the second set of functions. The reason for this is that these functions are usually monadic; if you use a function returning () in a monadic context but ignore the return value, GHC does not give a warning (since it will always return ()), but it does if the function does give a meaningful return value which you still ignore GHC will warn you. So e.g. do { sequence [print 1,print 2,print 3]; putStrLn "ignoring prev value" } will give a warning, but do { sequence_ [print 1,print 2,print 3]; putStrLn "ignoring prev value" } will not.

  • 2
    Returning () is also sometimes "easier". traverse_, for example, only requires a Foldable collection, because the collection does not need to be rebuilt in the new context, even though traverse requires Traversable. – HTNW Apr 19 at 1:54
  • I didn't know that @HTNW - thanks! – bradrn Apr 19 at 4:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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