








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









▪ If the input is 0, use factorial 0 = 1. ▪ If the input is not 0, check the guards: ▪ If n > 0, use the recursive case. ▪ If not (i.e., n is negative), use the otherwise case and throw an error.
o Example: For (1, "hello"), a is Int, b is String, so the type becomes (Int, String) - > (String, Int).
o What happens: ▪ Input: (True, 42), where a = Bool, b = Int. ▪ Matches x = True, y = 42. ▪ Returns (42, True). ▪ print displays (42, True). o Polymorphism: Works with Bool and Int, showing flexibility.
▪ map is a built-in function with type (a - > b) - > [a] - > [b], meaning it takes a function (here, triple) and a list, applies the function to each element, and returns a new list. ▪ map triple [1, 2, 3, 4] applies triple to each element: ▪ triple 1 = 3 ▪ triple 2 = 6 ▪ triple 3 = 9 ▪ triple 4 = 12 ▪ Result: [3, 6, 9, 12], which print displays.
Filter is a built-in Haskell function that takes a list and a condition (called a predicate function) and returns a new list containing only the elements that satisfy the condition. It’s a higher-order function because it takes a function as an input. Think of filter as a gatekeeper who checks each item in a list and only lets through the ones that pass a test.
This example uses filter to select short strings (length ≤ 3) from a list of strings. haskell -- Check if a string has length <= 3 isShort :: String - > Bool isShort str = length str <= 3 main :: IO () main = do
let words = ["cat", "dog", "elephant", "hi", "rhinoceros"] print (filter isShort words) -- Output: ["cat", "dog", "hi"]
▪ head "ball" = 'b', 'b' == 'b' → True. ▪ Compute length "ball" = 4, keep 4. ▪ For word = "dog": ▪ head "dog" = 'd', 'd' == 'b' → False, skip. ▪ For word = "banana": ▪ head "banana" = 'b', 'b' == 'b' → True. ▪ Compute length "banana" = 6, keep 6. ▪ Result: [4, 4, 6], which print displays.
Lazy evaluation: Covered