This is about syntactic sugar in Haskell. A simple Haskell program:
main = do
args <- getArgs
let first = head args
print first
I use binding in the first line (args <- getArgs
) and a pure assignment in the second one (let first = ...
). Is it possible to merge them together into a readable one-liner?
I understand that I can rewrite binding “de-sugared”:
main = do
first <- getArgs >>= ( return . head )
print first
But is there a nicer way, without cluttering the line with (>>=) and return?
Overview. We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.
(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.
liftM
and head
are all very well, but let us not forget pattern matching:
main = do { arg:_ <- getArgs; print arg }
or if you like layout
main = do
arg : _ <- getArgs
print arg
When possible, most Haskellers prefer pattern matching over head
and tail
.
Yet another possibility:
main = putStr . head =<< getArgs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With