mkUltra
mkUltra

Reputation: 3068

What does underscore at the end of the function mean in Haskell?

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

What does it mean?

Upvotes: 4

Views: 759

Answers (1)

bradrn
bradrn

Reputation: 8467

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 GHC does warn you if the function does give a meaningful return value which you ignore. 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.

Upvotes: 12

Related Questions