Haskell

Syntactic elements

  • A Haskell program (basically) consists of expressions and declarations

Expressions

  • Literals
  • Arithmetic expressions
  • Function applications
  • Conditionals
  • Identifiers (names)

Declarations

  • Bind expressions to names
  • Use the operator =
  • Top-level bindings
  • Local bindings

Expressions

Literals

In [ ]:
42
"Arthur Dent"
[1, 2, 3]
(42, "fortytwo")

Evaluates to the value itself

Arithmetic

In [ ]:
(1 + 2) * 3
3.14 * 2 * 17
3^2 + 4^2 == 5^2

Evaluates to the result of the operation

Function invocation

In [ ]:
max 23 42
length [1, 2, 3]
triple 3

Evaluates to the function value returned


Declarations

Bind expressions

In [ ]:
answer = 42
crew = ["Kirk", "Spock", "McCoy"]
  • Value 42 is bound to name answer
  • List of crew members is bound to name crew
  • Identifiers answer and crew can be used in other expression
  • They evaluate to the bound values

Bind functions

In [ ]:
triple x = x + x + x
hello name = "Hello " ++ name
  • Functions of one parameter are bound to names triple and hello
  • Functions triple and hello can be invoked in other expressions
  • They evaluate to the computed function value

Special expression syntax

Conditional if expression

In [ ]:
x = 1
if x < 2 then "Smaller than two" else "Bigger than 2"

if expression in a function declaration

In [ ]:
max a b = if a > b then a else b

Function declaration

3 Examples

{.haskell}
seven = 7
triple x = x + x + x
max a b = if a > b then a else b

Components

  • Function names (seven, triple, max)
  • Zero or more function parameters (a, b, x)
  • Function expression with identifiers bound to the function parameters

Function and parameter names

  • Must start with a lower-case character
  • Consist of alpha-numeric characters only

Function example

Consider these expressions

In [ ]:
3.141 * 5 * 5
3.141 * 42 * 42
3.141 * 17 * 17

Try to abstract that into a function

In [ ]:
circleArea r = 3.141 * r ^ 2

Recursive operations on lists

Task: Calculate the arithmetic mean of a list of numbers

$$ \bar{x} = \frac{1}{n}\left (\sum_{i=1}^n{x_i}\right ) = \frac{x_1+x_2+\cdots +x_n}{n} $$

The mean function

In [ ]:
mean list = totalSum list / count list

[Now implement count and totalSum]{.fragment}


Recursive operations on lists

Task: Calculate the number of elements in a list

The function count

In [ ]:
count list =
  if null list
    then 0
    else 1 + count (tail list)

Recursive operations on lists

Task: Calculate the sum of elements in a list of numbers

The function totalSum

In [ ]:
totalSum list =
  if null list 
    then 0
    else head list + totalSum (tail list)