Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are monads expressions, or are there statements in Haskell?

Tags:

haskell

monads

I have an ontological question about monads in haskell; I'm shaky on whether the language makes a distinction between statements and expressions at all. For example, I feel like in most other languages anything with a signature like a -> SomeMonadProbs () would be considered a statement. That said, since haskell is purely functional, and functions are composed of expressions, I'm a wee bit confused on what haskell would say about monads in terms of their expression-hood.

like image 509
jcc333 Avatar asked Sep 27 '13 13:09

jcc333


People also ask

Are there statements in Haskell?

Haskell has no statements, only expressions! In an imperative language like C or Java, there are expressions that denote small scale computations ( 2*x ), and. statements that handle sequencing, looping, conditionals, and all the large scale operation of the program.

What are monads in Haskell?

A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.

What are monads explain with example?

In functional programming, a monad is a software design pattern with a structure that combines program fragments (functions) and wraps their return values in a type with additional computation.

Why are monads useful?

monads are used to address the more general problem of computations (involving state, input/output, backtracking, ...) returning values: they do not solve any input/output-problems directly but rather provide an elegant and flexible abstraction of many solutions to related problems.


1 Answers

Monad is just one interface for interacting with expressions. For example, consider this list comprehension implemented using do notation:

example :: [(Int, Int)]
example = do
    x <- [1..3]
    y <- [4..6]
    return (x, y)

That desugars to:

[1..3] >>= \x ->
[4..6] >>= \y ->
return (x, y)

... and substituting in the definition of (>>=) for lists gives:

concatMap (\x -> concatMap (\y -> [(x, y)]) [4..6]) [1..3]

The important idea is that anything you can do using do notation can be replaced with calls to (>>=).

The closest thing to "statements" in Haskell are syntactic lines of a do notation block, such as:

x <- [1..3]

These lines do not correspond to isolated expressions, but rather syntactic fragments of an expression which are not self-contained:

[1..3] >>= \x -> ... {incomplete lambda}

So it's really more appropriate to say that everything is an expression in Haskell, and do notation gives you something which appears like a bunch of statements but actually desugars to a bunch of expressions under the hood.

like image 115
Gabriella Gonzalez Avatar answered Sep 26 '22 04:09

Gabriella Gonzalez