Programming Languages
Open the comand prompt / terminal, navigate to your desktop, and enter ghci. Open a code editor (e.g., Atom, Visual Studio Code, Sublime Text) and create a file activity05.hs; save it to the cs222 folder on your desktop. As you write functions, test them in ghci.
It is expected that you have read Ch. 4 of your Haskell book.
The map function, which is predefined in Haskell, is defined as follows:
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (a : ls) = (f a) : (map f ls)
It is a higher-order function (takes other functions as a parameter) which returns a list consisting of the image of the items in the original list under the function f.
toUpper, which is defined in Data.Char, to each item of the string. Test it out on an input string in ghci.
import Data.Char -- used for Char
import Data.List -- used later for insert
cap :: [Char] -> [Char]
cap [] = []
cap (a : ls) = (toUpper a) : (cap ls)
map function). Test it by calling cap2 "hello cs222".
cap2 :: [Char] -> [Char]
cap2 ls = map toUpper ls
absList :: [Int] -> [Int] that converts a list of integers into a list of absolute values in the original list. Use the map function. Test it. For example:
*Main> absList [1, (-2), 3, (-4)]
[1,2,3,4]
stringLengths which takes a list of Strings and converts it to a list of integers, where each integer in the result is the list of the corresponding string in the argument. Use the map function. Test it. For example:
*Main> stringLengths ["hi", "this", "is", "cool"]
[2,4,2,4]
The foldr function, which is predefined in Haskell, is defined as follows:
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [] = z
foldr f z (x : xs) = f x (foldr f z xs)
It is a higher-order function (takes other functions as a parameter) which takes a list and replaces the cons operator : with the given function f, and the empty list with the given value z.
For example,
foldr (+) 0 [1, 2, 3] == (1 + 2 + 3 + 0)
How? [1, 2, 3] is just syntactic sugar for (1 : (2 : (3 : []))). We first replaced the cons operator : with
(1 + (2 + (3 + [])))
And lastly, we told foldr to replace the empty list [] with 0.
(1 + (2 + (3 + 0)))
insert takes an integer and a sorted list and places the integer where it belongs in the sorted list. Add the following new function and test it with an unsorted list as input.
insertionSort :: [Int] -> [Int]
insertionSort ls = foldr insert [] ls
sumAll :: [Int] -> Int
sumAll ls = foldr (+) 0 ls
coolFactorial :: [Int] -> Int which uses foldr to multiply all the numbers in the list, using 1 as the starting product.Submit your file to Moodle which has all working function definitions.