module Work1 where import Data.Char -------------------------------------------------------------------------------- -- Operating on *all* elements in a list -- Examples of using list comprehension -- sumSquares n gives the sum of the squares of the numbers from 1 to n sumSquares :: Integer -> Integer sumSquares n = sum [i*i | i <- [1..n]] -- allCAPS s changes each character to upper case allCAPS :: String -> String allCAPS str = [toUpper c | c <- str] -- takeWords n s returns the first n words of s takeWords :: Int -> String -> String takeWords n str = unwords \$ take n \$ words str -- capitalize s capitalizes all words in s capitalize :: String -> String capitalize str = unwords [cap w | w <- words str] where cap :: String -> String cap (c:str) = toUpper c : str -- Socrative (later) -- toNorwegian a sentence to Norwegian -- "inte" -> "ikke" -- "jag" -> "jeg" -------------------------------------------------------------------------------- -- Operating on *some* elements in a list (filtering) -- keepPositives as delete all negative numbers from as keepPositives :: [Integer] -> [Integer] keepPositives as = [a | a <- as, a > 0] -- divisors n lists the (positive) divisors of n divisors :: Integer -> [Integer] divisors n = [f | f <- [1..n], n `mod` f == 0] -- isPrime n checks if n is a (positive) prime number isPrime :: Integer -> Bool isPrime n = length (divisors n) == 2 -- censor s deletes all lines in s which contain the word "money" -------------------------------------------------------------------------------- -- Multiple list generators -- dices n returns the ways that a pair of dices can result in the sum n dices :: Integer -> [(Integer,Integer)] dices n = [(d1,d2) | d1 <- [1..6], d2 <- [1..6], d1+d2 == n] -- check_max n checks that the max function is correct for all arguments from 0 -- to n check_max :: Integer -> Bool check_max n = and [max a b >= a && max a b >= b | a <- [0..n], b <- [0..n]] -- closestPoints ps gives the distance between the closest (non-equal) points in -- the list ps -- @ patterns