Download presentation
Presentation is loading. Please wait.
1
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering CSCE 330 Programming Language Structures Haskell Fall 2005 Marco Valtorta mgv@cse.sc.edu
2
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Simple Function Definition Examples from Sebesta fact 0 = 1 fact n = n * fact (n -1) fib 0 = 1 fib 1 = 1 fib (n + 2) = fib (n + 1) + fib n
3
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Guards and otherwise fact n | n == 0 = 1 | n > 0 = n * fact (n – 1) fact will not loop forever for a negative argument! sub n | n < 10 = 0 | n > 100 = 2 | otherwise = 1
4
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Local scope: where quadratic_root a b c = [minus_b_over_2a – root_part_over_2a, minus_b_over_2a + root_part_over_2a] where minus_b_over_2a = -b / (2.0 * a) root_part_over_2a = sqrt(b ^ 2 – 4.0 * a * c) / (2.0 * a)
5
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering List comprehensions, generators, and tests List comprehensions are used to define lists that represent sets, using a notation similar to traditional set notation: [body | qualifiers], e.g., [n * n * n | n <- [1..50]] defines a list of cubes of the numbers from 1 to 50 Qualifiers can be generators (as above) or tests The following function returns the list of factors of n factors n – [i | i <- [1.. n div 2], n mod i == 0]
6
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Quicksort in Haskell sort [] = [] sort (h : t) = sort [b | b <- t, b <= h] ++ [h] ++ sort [b | b h] ++ is for concatenation
7
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Lazy evaluation Lazy evaluation allows infinite data structures, e.g.: positives = [0..] squares = [n * n | n <- [0..]] member squares 16 member [] b = False member (a:x) b = (a == b) || member x b member2 (m:x) n | m < n = member2 x n | m == n true otherwise = False
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.