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 activity06.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. 5 of your Haskell book.
In ghci
, type :t map
to see the type signature of the map
function.
Repeat this process to see the type signature of the doubling function. Type :t (* 2)
.
(* 2) -- "doubling" function
(+ 4) -- "add 4" function
(1 /) -- "reciprical" function
(/ 4) -- "one fourth" function
(> 5) -- "bigger than 5?" function
(== ' ') -- "equals blank" function
doubleAll :: [Int] -> [Int]
which uses the doubling function and map
to double each item in a list. For example:
*Main> doubleAll [1..5]
[2,4,6,8,10]
addOneAll
which uses map
and the “increment” function to add 1 to all elements. For example:
*Main> addOneAll [1..5]
[2,3,4,5,6]
powerAll
which uses map
and constructs a list of values formed by 2 to the power of the corresponding number in the list. For example:
*Main> twoPowerAll [1,3,4]
[2,8,16]
ghci
:
[ x | x <- [1..100], x < 10]
Use list comprehension to implement the function quickSort
which takes a unique list of numbers and sorts it using the quicksort algorithm, using the head of the list as the pivot. Recall that quicksort works by selecting a pivot to partition the list into a list of items less than the pivot and a list of items greater than the pivot. Then, it recursively calls quicksort to sort the smaller sized lists, and concatenates them together with the pivot after each list is sorted. Hint: refer to example 12 of book for help.
Assuming that a list is ordered, write a function insert'
(yes - with apostrophe) which takes a list and a new element and returns the list with the element inserted in the correct position in the list. Use list comprehension for your solution.
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
fizzBuzz
which takes a list of numbers. It should use a list comprehension to output a list of strings corresponding to the input numbers. Write “fizz” if the number is divisible by 3, “buzz” if it is divisible by 5, and “fizz buzz” if it is divisible by both. Otherwise, it should output the number as a string. Use show
to convert an integer to a string. For example:
*Main> fizzBuzz [1..15]
["1","2","fizz","4","buzz","fizz","7","8","fizz","buzz","11","fizz","13","14","fizz buzz"]
elem
returns True or False whether a given element is in a list. Use it and a list comprehension to write a function removeUpperCase
which takes a string and returns a string with all uppercase characters removed. For example:
*Main> removeUppercase "Hello There"
"ello here"
Submit your file to Moodle which has all working function definitions.