90 likes | 324 Views
Haskell. Chapter 1, Part II. List Comprehension. List comprehensions are a way to filter, transform and combine lists Similar to mathematical set comprehensions {2 * x | x e N, X <= 10} In Haskell: [x * 2 | x <- [1..10]] “draw” our elements from the list [1..10]
E N D
Haskell Chapter 1, Part II
List Comprehension • List comprehensions are a way to filter, transform and combine lists • Similar to mathematical set comprehensions • {2 * x | x e N, X <= 10} • In Haskell: • [x * 2 | x <- [1..10]] • “draw” our elements from the list [1..10] • so x takes on each value from 1 to 10 • part before the pipe (|) is the output
With a predicate • [x * 2 | x <- [50..100], x `mod` 7 == 3] • Using a predicate in this way is called filtering • Can separate predicates with a comma • [x | x <- [10..20], x /= 13, x /= 15, x /= 19] • Can draw from several lists • [x+y| x<-[1,2,3], y <- [10,100, 1000]] • result: [11,101,1001,12,102,1002,13,103,1003]
More list comprehensions • Can use a temporary variable • length' xs = sum [1 | _ <- xs] • Can be used with strings (they’re lists too) • removeNonUppercasest = [c | c <- st, c `elem` ['A'..'Z']] • Nested list comprehensions • -- let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]] • removeOddxxs = [[x | x <- xs, even x] | xs <- xxs]
Tuples • Used to store several heterogeneous elements as a single value • Tuples have a fixed size • Elements surrounded by parentheses • (1,3) • (3, ‘a’, “hello”) • (50, 50.4, “hello”, ‘b’) • tuple of size 2 is a different type from tuple of size 3 • tuples with different member elements are different types
More tuples • Storing pairs is common in Haskell • Useful functions to manipulate: • fst • snd • zip [1,2,3] [4,5,6] => [(1,4),(2,5),(3,6)] • zip [1..] ["apple", "orange", "banana"] => [(1,"apple"),(2,"orange"),(3,"banana")]
Tuples in list comprehensions • Generate tuples • triples = [(a,b,c) | c <- [1..10], a<-[1..10], b<-[1..10]] • Generate tuples with filter • rightTriangle = [(a,b,c) | c <- [1..10], a<-[1..c], b<-[1..a], • a^2 + b^2 == c^2]
Play and Share • evenCubes[1..20] • [8,64,216,512,1000,1728,2744,4096,5832,8000] • onlyBig[200,30,50,20,120] 100 • [200,120] • noDiagonal[1..4] • [(1,2),(1,3),(1,4),(2,1),(2,3),(2,4),(3,1),(3,2),(3,4),(4,1),(4,2),(4,3)] • diagonal 10 • [(0,0),(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),(8,8),(9,9),(10,10)] • countOdd[1..30] • 15 • evenOddPairs[1..4][20, 17, 23, 42] • [(2,17),(4,17),(2,23),(4,23)] • removeDigits"abc1d23A.98" • "abcdA.“ • ends [[4,5,6],[1,2],[7,1,0]] • [6,2,0] * These are parameters