# User:Benmachine/Non-strict semantics

### From HaskellWiki

Benmachine (Talk | contribs) (New page: An expression language is said to have '''non-strict semantics''' if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to...) |
Benmachine (Talk | contribs) |
||

Line 32: | Line 32: | ||

</haskell> | </haskell> | ||

− | in fact has the value <hask>Just 0</hask>. The program does not try to compute <hask>noreturn 5</hask> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result are computed. This is called '''outermost-first''' evaluation because | + | in fact has the value <hask>Just 0</hask>. The program does not try to compute <hask>noreturn 5</hask> because it is irrelevant to the overall value of the computation: only the values that are necessary to the result are computed. This is called '''outermost-first''' evaluation because you first look at <hask>lookup</hask> to see if it needs to use its arguments, and only if it does do you look at what those arguments are. The upshot is that you can give a function an argument that it doesn't look at, and it doesn't matter if it's <hask>⊥</hask> or not, the function will return a value anyway. Such functions are not strict, i.e. they satisfy <hask>f ⊥ ≠ ⊥</hask>. Practically, this means that Haskell functions need not completely compute their arguments before using them, which is why e.g. <hask>take 3 [1..]</hask> can produce <hask>[1,2,3]</hask> even though it is given a conceptually infinite list. |

=== Why? === | === Why? === | ||

The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics means that only the things that are needed for the answer are evaluated, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time spent working out what should and shouldn't be evaluated is time wasted. For this reason, non-strict programs tend to be a little slower than strict programs. | The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics means that only the things that are needed for the answer are evaluated, but if you write your programs carefully, you'll only compute what is absolutely necessary ''anyway'', so the extra time spent working out what should and shouldn't be evaluated is time wasted. For this reason, non-strict programs tend to be a little slower than strict programs. | ||

+ | |||

+ | However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate ''production'' and ''consumption'' of data: don't know how many prime numbers you're going to need? Just make `primes` a list of ''all'' prime numbers, and then which ones actually get ''generated'' depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself. | ||

+ | |||

+ | What this means in practice is that in Haskell you can often write your function as a simple composition of other general functions, and still get the behaviour you need, e.g: | ||

+ | |||

+ | <haskell> | ||

+ | any :: (a -> Bool) -> [a] -> Bool | ||

+ | any p = or . map p | ||

+ | </haskell> | ||

+ | |||

+ | Because <hask>or</hask> uses non-strictness to stop at the first <hask>True</hask> in the input, <hask>map</hask> doesn't even need to know that only the first half of the list might be needed. We can write <hask>map</hask> in the completely straightforward and obviously correct way, and still have it interact well with <hask>or</hask> in this way. In a strict langauge, you'd have to write the recursion out manually: | ||

+ | |||

+ | <haskell> | ||

+ | any p [] = False | ||

+ | any p (x:xs) | ||

+ | | p x = True | ||

+ | | otherwise = xs | ||

+ | </haskell> | ||

+ | |||

+ | since in strict languages only builtin control structures can decide whether some bit of code gets executed or not: ordinary functions like <hask>or</hask> can't. It's this additional power that Haskell has that leads people to say you can define your own control structures as normal Haskell functions, that makes lists act as for loops, which you can break or continue as necessary, doing no more work than required. |

## Revision as of 20:40, 4 May 2012

An expression language is said to have **non-strict semantics** if expressions can have a value even if some of their subexpressions do not. Haskell is one of the few modern languages to have non-strict semantics by default: nearly every other language has strict semantics, in which if any subexpression fails to have a value, the whole expression fails with it.

### 1 What?

Any sufficiently capable programming language is *non-total*, which is to say you can write expressions that do not produce a value: common examples are an infinite loop or unproductive recursion, e.g. the following definition in Haskell:

noreturn :: Integer -> Integer noreturn x = negate (noreturn x)

or the following Python function:

def noreturn(x): while True: x = -x return x # not reached

both fail to produce a value when executed. We say that `noreturn x` is undefined, and write `noreturn x = ⊥`.

In Python the following expression:

{7: noreturn(5), 2: 0}[2]

also fails to have a value, because in order to construct the dictionary, the interpreter tries to work out `noreturn(5)`, which of course doesn't return a value. This is called **innermost-first** evaluation: in order to call a function with some arguments, you first have to calculate what all the arguments are, starting from the innermost function call and working outwards. The result is that Python is strict, in the sense that calling any function with an undefined argument produces an undefined value, i.e. `f(⊥) = ⊥`.

In Haskell, an analogous expression:

lookup 2 [(7, noreturn 5), (2, 0)]

**outermost-first**evaluation because you first look at

### 2 Why?

The important thing to understand about non-strict semantics is that it is not a performance feature. Non-strict semantics means that only the things that are needed for the answer are evaluated, but if you write your programs carefully, you'll only compute what is absolutely necessary *anyway*, so the extra time spent working out what should and shouldn't be evaluated is time wasted. For this reason, non-strict programs tend to be a little slower than strict programs.

However, the real and major advantage that non-strictness gives you over strict languages is you get to write cleaner and more composable code. In particular, you can separate *production* and *consumption* of data: don't know how many prime numbers you're going to need? Just make `primes` a list of *all* prime numbers, and then which ones actually get *generated* depends on how you use them in the rest of your code. By contrast, writing code in a strict language that constructs a data structure in response to demand usually will require first-class functions and/or a lot of manual hoop-jumping to make it all behave itself.

What this means in practice is that in Haskell you can often write your function as a simple composition of other general functions, and still get the behaviour you need, e.g:

any :: (a -> Bool) -> [a] -> Bool any p = or . map p

any p [] = False any p (x:xs) | p x = True | otherwise = xs