This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 1 PROGRAMMING IN HASKELL Chapter 4  Defining Functions 2 Conditional Expressions As in most programming languages, functions can be defined using conditional expressions . abs :: Int → Int abs n = if n ≥ 0 then n else n abs takes an integer n and returns n if it is nonnegative and n otherwise. 3 Conditional expressions can be nested: signum :: Int → Int signum n = if n < 0 then 1 else if n == 0 then 0 else 1 ❚ In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals. Note: 4 Guarded Equations As an alternative to conditionals, functions can also be defined using guarded equations . abs n  n ≥ 0 = n  otherwise = n As previously, but using guarded equations. 5 Guarded equations can be used to make definitions involving multiple conditions easier to read: ❚ The catch all condition otherwise is defined in the prelude by otherwise = True. Note: signum n  n < 0 = 1  n == 0 = 0  otherwise = 1 6 Pattern Matching Many functions have a particularly clear definition using pattern matching on their arguments. not :: Bool → Bool not False = True not True = False not maps False to True, and True to False. 7 Functions can often be defined in many different ways using pattern matching. For example (&&) :: Bool...
View
Full Document
 Spring '10
 Valtorta
 or operator, Haskell, lambda expressions

Click to edit the document details