chapter4 - 1 PROGRAMMING IN HASKELL Chapter 4 Defining...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the 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 non-negative 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

This note was uploaded on 06/11/2011 for the course CSCE 330 taught by Professor Valtorta during the Spring '10 term at Columbia SC.

Page1 / 24

chapter4 - 1 PROGRAMMING IN HASKELL Chapter 4 Defining...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online