Title | Homework 4 and solutions on Haskell programming language |
---|---|
Course | Prog Paradigms |
Institution | Wichita State University |
Pages | 3 |
File Size | 117.4 KB |
File Type | |
Total Downloads | 24 |
Total Views | 128 |
Homework 4 and solutions on Haskell programming language...
Course: Programming Paradigms Course number: CS 410 Homework and solutions on Haskell programming language Note that: Questions are in times new roman fonts. Solutions are written in courier new fonts. “--“ double dash sign in front of any statement means everything on that line is commented and not part of the code to be run.
Homework 4 Create a Haskell Script text file ha4.hs and write in that file Haskell definitions of the functions described in the following questions. Remember to employ recursion in your solutions. 1. [10 marks] The Collatz Conjecture is as follows: Take any positive integer n. If n is even, divide it by 2 to obtain n/2. But if n is odd, multiply it by 3 and add 1 to obtain 3n+1. Repeat this process indefinitely. The conjecture states that no matter which number you start with, you always reach 1 eventually. For example, starting from n = 12, the following 9 steps reach 1: 12, 6, 3, 10, 5, 16, 8, 4, 2, 1. Write a function collatz n, which takes as input an integer n, and returns the number of steps required to reach 1. As a special case, return -1 if n is not positive.
The Haskell interaction may look like: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 2.
Prelude> collatz 12 9 Prelude> collatz 25 23 Prelude> collatz 0 -1 Prelude> collatz 1 0 Prelude> collatz 500 110 [10 marks] Write a function lensort x, which takes as input a list x of sublists, and sorts the sublists in x according to their lengths. Feel free to adopt any of the three list sorting methods done in class.
The Haskell interaction may look like:
1.
Prelude> lensort [ [1, 2, 3], [4, 5], [6, 7, 8], [9, 10], [11, 12, 13, 14], [15, 16], [17] ]
2. 3. 4.
[ [17], [4, 5], [9, 10], [15, 16], [1, 2, 3], [6, 7, 8], [11, 12, 13, 14] ]
Prelude> lensort [ "the", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog" ] 5. [ "a", "the", "fox", "dog", "over", "lazy", "quick", "brown", "jumps" ] 6. Submit your ha4.hs file here as your Blackboard submission for this assignment.
Sol ut i ont ohomewor k4 -- collatz -- This can be implemented in a straightforward way by recursion. The base -- cases are for n == 1 and n < 1. The recursive cases simply employ the -- definition of collatz, after checking even-ness of n. collatz' :: Integer -> Integer collatz' 1 = 0 collatz' n | (n < 1) = -1 | (n `mod` 2 == 0) = 1 + collatz' (n `div` 2) | otherwise = 1 + collatz' (3 * n + 1) ---------------------------------------------------------------------------- lensort -- This one is straightforward too. We can do quicksort on the given list, -- based on not the "values" of the list's elements, but their "lengths". lensort' :: [[t]] -> [[t]] lensort' [] = [] lensort' (h:t) = let
small = [ x | x...