views:

268

answers:

3

hi i prepare myself for the exams and i am styding on previous past papers. could anybody give me a model answer to the following question,it would be very helpful to me to work through the answer!

  1. a) Show how to read a line using getLine and use putStrLn to write out the capitalized version of the line. (15%)

    b) Consider the following function definition:

    mystery :: Ord a => a -> [a] -> [a]
    mystery x [] = []
    mystery x (y:ys)
        | x <= y = y : mystery x ys
        | otherwise = x : mystery x ys
    

    i) Explain the Ord constraint on the first line. (10%)

    ii) Give the value of the expression mystery 3 [2,7,1,8]. (10%)

    iii) What does the function do? (10%)

    iv) Define an equivalent function, but without using recursion. (15%)

+1  A: 

a) Show how to read a line using getLine and use putStrLn to write out the capitalized version of the line. (15%)

import Data.Char

main = do
  line <- getLine
  putStrLn (map toUpper line)

b) Consider the following function definition:

mystery :: Ord a => a -> [a] -> [a]
mystery x [] = []
mystery x (y:ys)
    | x <= y = y : mystery x ys
    | otherwise = x : mystery x ys

i) Explain the Ord constraint on the first line. (10%)

mystery accepts value of type 'a' and 'a' list containing type 'a' values. mystery returns a list of type 'a'. 'a'-type must implement Ord -class.

ii) Give the value of the expression mystery 3 [2,7,1,8]. (10%)

[3,7,3,8]

iii) What does the function do? (10%)

mystery clamps the list with a minimum value.

iv) Define an equivalent function, but without using recursion. (15%)

clampLower :: Ord a => a -> [a] -> [a]
clampLower x = map (max x)
Cheery
+1  A: 
  1. Ord a means that the type a must support ordering, that is, support the <, >, <=, >= operators. So mystery can be only applied on a value of that type and a list of that type.

  2. The result is

    mystery 3 [2,7,1,8] = [3,7,3,8]
    
  3. The function replaces all values in the list smaller than x by x.

  4. It's not possible to define such a function without recursion in Haskell, but it can be hidden using a different function such as map:

    mystery x s = map (\y -> if x <= y then y else x) s
    
Roman Plášil
+1  A: 

b) i) The Ord means that type a can be ordered. (i.e. matahematic greater than less than operators can be used on type a) ii)

mystery 3 [2,7,1,8]

3 : mystery 3 [7,1,8]
3 : 7 : mystery 3 [1,8]
3 : 7 : 3 : mystery 3 [8]
3 : 7 : 3 : 8 : mystery 3 []
3 : 7 : 3 : 8 : []

= [3,7,3,8]

3) It compares the input x, with the list and replaces all values that are less than x with x.

4) Can you do some kinf of list function? (my haskell is v rusty)

x:xs:xss where [ x >= xs ? x : xs | x->(xs:xss)]

Dynite