{- CSE 341 Winter 2014 Sujit Packiaraj -} -- for isUpper import Data.Char -- Function which computes x! factorial x = if x == 0 then 1 else x * factorial (x - 1) -- Function which sums all of the elements in the list xs -- Does not use case expressions sum_all xs = if null xs then 0 else head xs + sum_all (tail xs) -- Function which takes a tuple (x, y, z) and sums x, y, and z sum_all_tuples (x, y, z) = x + y + z -- Function which sums its curried parameters x, y, and z sum_all_curry x y z = x + y + z -- This function is equivalent to sum_all_curry -- Uses anonymous functions to show how currying is actually implemented currying_explained x = (\y -> (\z -> x + y + z)) -- We are calling currying_exlained with 1, which returns a function -- which takes in one more parameter (y). x is set to 1 internally -- we_have_x_now_need_y = (\y -> (\z -> 1 + y + z)) we_have_x_now_need_y = currying_explained 1 -- We are calling we_have_y_now_need_z with 2, which returns a function -- which takes in one more parameter (z). y is set to 2 internally -- we_have_y_now_need_z = (\z -> 1 + 2 + z)) we_have_y_now_need_z = we_have_x_now_need_y 2 -- result1 == result2 -- result1 == 1 + 2 + 3 result1 = we_have_y_now_need_z 3 result2 = currying_explained 1 2 3 -- Function which takes a parameter and adds 3 to it -- Demonstrates currying/partial function application add3 = sum_all_curry 1 2 -- Function which takes a parameter x and adds 1 to it increment x = x + 1 -- Function which takes a list and outputs a list with 1 added to each element increment_list = (map increment) -- Function which takes a [Char] and returns a [Bool] representing which isCaps = (map isUpper) -- Function which removes the lower case characters from a String removeLowerCase = (filter isUpper) -- Same as sum_all except uses pattern matching sum_all2 [] = 0 sum_all2 (x:xs) = x + sum_all2 xs -- Function which sums up the values of its two parameter lists -- Uses case expressions and pattern matching sum_all_two xs ys = case (xs, ys) of ([], []) -> 0 ([], y:ys') -> y + sum_all_two [] ys' (x:xs', []) -> x + sum_all_two xs' [] (x:xs', y:ys') -> x + y + sum_all_two xs' ys' -- Equivalent to sum_all_two sum_all_two2 [] [] = 0 sum_all_two2 [] (y:ys) = y + sum_all_two2 [] ys sum_all_two2 (x:xs) [] = x + sum_all_two2 xs [] sum_all_two2 (x:xs) (y:ys) = x + y + sum_all_two2 xs ys -- Implementation of the inbuilt map function using case expressions my_map f xs = case xs of [] -> [] (a:as) -> (f a) : (my_map f as) -- Function which simulates an if statement my_if test a b = if test then a else b -- result3 == 1.0 -- Lazy evaluation for the win!!! result3 = my_if True (1.0) (1.0 / 0)