12/08/2020 Code (Week 1)
Code (Week 1) Basic Functions
Higher Order Functions
toCartesian :: (Double, Double) -> (Double, Double)
toCartesian = \(r, theta) -> let
y = r * sin theta
x = r * cos theta
in (x, y)
twice :: (a -> a) -> (a -> a) twice f a = f (f a) — Equation 1
double :: Int -> Int
double = \x -> x * 2
{-
twice twice double 3
== (twice twice double) 3 – Equation 1
== (twice (twice double)) 3
== (twice quadruple) 3 – defn. of quadruple
== quadruple (quadruple 3) – Equation 1
== 48
-}
quadruple :: Int -> Int
quadruple = twice double — defn of quadruple
Common Words Problem
import Data.Char(toLower)
import Data.List(group,sort,sortBy)
breakIntoWords :: String -> [String]
www.cse.unsw.edu.au/~cs3141/20T2/Week 01/1Vid/Code.html
1/3
12/08/2020 Code (Week 1)
List Functions
breakIntoWords = words
convertIntoLowercase :: [[Char]] -> [String]
convertIntoLowercase = map (map toLower)
sortWords :: [String] -> [String]
sortWords = sort
type Run = (Int, String)
countAdjacentRuns :: [String] -> [Run]
countAdjacentRuns = convertToRuns . groupAdjacentRuns
— [“hello”,”hello”,”world”] –> [[“hello”,”hello”],[“world”]] groupAdjacentRuns :: [String] -> [[String]]
groupAdjacentRuns = group — head :: [a] -> a
convertToRuns :: [[String]] -> [Run]
convertToRuns = map (\ls-> (length ls, head ls))
sortByRunSize :: [Run] -> [Run]
sortByRunSize = sortBy (\(l1, w1) (l2, w2) -> compare l2 l1)
takeFirst :: Int -> [Run] -> [Run]
takeFirst = take
generateReport :: [Run] -> String
generateReport = unlines . map (\(l,w) -> w ++ “:” ++ show l )
— (\x -> f x) == f
mostCommonWords :: Int -> (String -> String)
mostCommonWords n =
generateReport
. takeFirst n
. sortByRunSize
. countAdjacentRuns
. sortWords
. convertIntoLowercase
. breakIntoWords
www.cse.unsw.edu.au/~cs3141/20T2/Week 01/1Vid/Code.html
2/3
12/08/2020 Code (Week 1)
— in maths: f(g(x)) == (f o g)(x)
myMap :: (a -> b) -> [a] -> [b]
myMap f [] =[]
myMap f (x:xs) = (f x) : (myMap f xs)
— 1 : 2 : 3 : []
— 1 + 2 + 3 + 0
sum’ :: [Int] -> Int sum’ [] = 0
sum’ (x:xs) = x + sum xs
— [“hello”,”world”,”!”] -> “helloworld!” — “hello”:”world”:”!”:[]
— “hello”++”world”++”!”++[]
concat’ :: [[a]] -> [a]
concat’ [] =[]
concat’ (xs:xss) = xs ++ concat xss
foldr’ :: (a -> b -> b) -> b -> [a] -> b foldr’ f z [] =z
foldr’ f z (x:xs) = x `f` (foldr’ f z xs)
sum” = foldr’ (+) 0
concat” = foldr’ (++) []
filter’ :: (a -> Bool) -> [a] -> [a]
filter’ p [] = []
— filter’ p (x:xs) = if p x then x : filter’ p xs — else filter’ p xs filter’ p (x:xs)
| p x = x : filter’ p xs
| otherwise = filter’ p xs
www.cse.unsw.edu.au/~cs3141/20T2/Week 01/1Vid/Code.html
3/3