Skip to content
UoL CS Notes

Lecture 4-1

COMP105 Lectures

IF

Differences Between Imperative and Functional

In imperative languages if changes the control flow but in functional languages there is no control flow.

Functional if gives a value that you will return based on a test.

if (1==1) then "yes" else "no"

Rather than controlling flow, functional if chooses between two alternatives and is a pure function.

f x = (if x > 10 then 1 else 0) + 2

The functional if is more commonly known as the ternary operator as it has three arguments.

Things of Note

  • For a functional if both branches much always be present.
    • A pure function must always return a value.
  • Both branches must have the same type.
    • This is because Haskell is strongly typed meaning that a single function can only return values of the same type.
  • Nested ifs are not recommended and there are better ways to complete the same task.

Structure of an IF

if A then B else C

A, B or C may be anything that can evaluate to a single value. This can be a value itself or another function.

Exercises

  1.  between36 x = if (x > 3 && x < 6) then "yes" else "no"
    
  2.  min' x y = if x < y then x else y
    
  3.  max3 x y z = if (x > y && x > z) then x else (if y > z then y else z)