Different type signatures/lengths are considered different types. Tuples: collection of values with a fixed length, but may have different types in each position. Integer: arbitrary-precision integer: Prelude> let base=2 :: Int …or queried with the GHCi :t command: Prelude> :t 6 Types can be explicitly declared with the :: syntax: val :: Int Functions and arguments start with lowercase. Īll type names start with a uppercase character. ![]() Lists which contain several values of a single type, written.Int: fixed-precision signed integer (usually 64-bit).= postfix 1 (postfix 2 (postfix 3 (postfix 4 ))) It's (usually?) possible to swap foldr and foldl if you change the operation appropriately. = More List Processing Haskell wiki: Foldr Foldl Foldl' = prefix (prefix (prefix (prefix 1) 2) 3) 4 = oneMore (oneMore (oneMore 0 'a') 'b') 'c' For example: myLength xs = foldl oneMore 0 xs More List Processingįoldr and foldl are surprisingly flexible. If there's a choice, foldl should be faster, since it's working from the head of the list (but there's more to say about that, later). The foldr function does the same thing, but associates the other way: foldr (+) 0 the zero: correct result for an empty list, and where to start the accumulator.the operation: function that combines the accumulator and an element.MySum' xs = foldl (+) 0 xs Haskell wiki: Fold Learn You A Haskell: folds Then, an equivalent fold: mySum' xs = foldl (+) 0 xs More List Processing Important points: the operation is (+) and the starting point (result for ) is 0. … but not foldr: used to apply a function across a list.Īn example: sum the values in a list. Where divides a b = (a `mod` b) = 0 More List Processingīoth map and filter duplicate things we can do with list comprehensions (or recursion): use whichever is easier to read in the specific situation. We could have defined divisors with filter as: divisors n = filter (divides n) More List Processingįilter: Take only elements of a list that meet some condition. Map: apply a function to each element in a list. ![]() There are more built-in tools that are worth mentioning… Processing lists so far: list comprehensions and recursion on lists. SplitAt: chop a list in two at a specific position. TakeWhile/ dropWhile: take/drop while a condition is true. Take/ drop: get/throw away the first elements from a list. Head/ tail: the first/rest of the list (but consider a cons pattern, which might be more readable). ![]() There are many ways to dissect lists in Haskell. Sometimes it's necessary to have a function, even though you have an operation defined as an operator… Parts of Lists Sometimes code can be more readable if you swap functions and operators: I often write a `div` 2 for symmetry with a / 2. They can be interchanged: (+) and (&) are functions `div` and `take` and `someFunc` are operators.
0 Comments
Leave a Reply. |