Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is <|> in haskell?

I am still learning haskell and looking at the snap web framework. In their hello world example there is a thingy that looks like <|>

site :: Snap ()
site =
    ifTop (writeBS "hello world") <|>
    route [ ("foo", writeBS "bar")
          , ("echo/:echoparam", echoHandler)
          ] <|>
    dir "static" (serveDirectory ".")

Googling for this is surprisingly challenging, and the snap documentation simply uses <|> as a noun. What is it, and what does it do?

like image 688
Fresheyeball Avatar asked May 17 '14 22:05

Fresheyeball


People also ask

What does a period do in Haskell?

In general terms, where f and g are functions, (f . g) x means the same as f (g x). In other words, the period is used to take the result from the function on the right, feed it as a parameter to the function on the left, and return a new function that represents this computation."

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.

What does dollar mean in Haskell?

The dollar sign, $ , is a controversial little Haskell operator. Semantically, it doesn't mean much, and its type signature doesn't give you a hint of why it should be used as often as it is. It is best understood not via its type but via its precedence.

What does Colon do in Haskell?

In Haskell, the colon operator is used to create lists (we'll talk more about this soon). This right-hand side says that the value of makeList is the element 1 stuck on to the beginning of the value of makeList .


2 Answers

It's a method in the Alternative typeclass in the module Control.Applicative in the base package.

Typically it means that you're dealing with a kind of computation which can fail and continue. If both x and y are typed as m a where m tags this kind of computation we're talking about then

x <|> y :: m a

is a computation which "tries" x and if it fails then "tries" y. Such kinds of computation instantiate Alternative.

like image 128
J. Abrahamson Avatar answered Oct 26 '22 19:10

J. Abrahamson


Quoting the Snap tutorial

If you’re not familiar with Haskell, you may be wondering about the <|>. It is simply a binary operator that evaluates its first argument, and if it failed, evaluates the second. If the first argument succeeded, then it stops without evaluating the second argument.

The site function uses <|> to connect three different functions that guard what page gets rendered. First, the ifTop function runs. This function succeeds if the requested URL is http:// site.com. If that happens, then Snap sends a response of “hello world”. Otherwise the route function is executed.

like image 31
chi Avatar answered Oct 26 '22 19:10

chi