Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix binding (<-) and assignment (let) in one line? (in Haskell)

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?

like image 857
sastanin Avatar asked Mar 18 '09 16:03

sastanin


People also ask

What is pattern matching in Haskell?

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.

What does -> mean in Haskell?

(->) 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.


2 Answers

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.

like image 172
Norman Ramsey Avatar answered Sep 18 '22 17:09

Norman Ramsey


Yet another possibility:

main = putStr . head =<< getArgs
like image 28
Jonas Avatar answered Sep 19 '22 17:09

Jonas