Functional Programming (H)
1. What is the difference between an expression and a statement in an imperative programming language
Expressions denote small scale computations that return a value
Statements handle sequencing, looping, conditionals, and all the large scale operation of a program
Expressions determine control flow and are often composed of statements
2. What is the result of the following expression in Haskell, where sqrt returns the square root of its argument:
sqrt 16+9
13
5
3. What is the result of the following expression in Haskell, where sqrt returns the square root of its argument:
sqrt (16+9)
13
5
4. Give one reason why the following code is incorrect in Haskell:
x = 4 x = ((x * 2))
Because there are too many parentheses
Because you can assign an expression to a name only once
5. What is the result of the expression
abs -6
in Haskell, where abs returns the absolute value of its argument.
6
An error
6. In Haskell, what is another appropriate name for this style of expression:
n = n + 1
An equation
An assignment
7. Is it valid to write
n = n + 1
in Haskell
No, it is a syntax error
Yes, it is a valid expression
8. Does the evaluation order of Haskell sub-expressions affect the overall value of the expression?
No, evaluation order does not affect the final value.
If expressions are evaluated in a different order, then the final value might be different.
9. What is the difference between a named function and a lambda function assigned to a variable? For example:
f x = x + 1 -- or f = \x -> x+1
It is less efficient to define functions in terms of lambdas.
There is no meaningful difference.
10. Given the definition:
sum_ratio = \x y z -> (x + y) / z
then what is the value of:
1 + 4* sum_ratio 4 2 3
5
9
11. What does the following expression evaluate to?
['a','d' .. 'z']
“adgjmpsvyâ€
“adzâ€
12. Given a list xs, what does the following expression evaluate to?
[]++xs == xs++[]
False
True
13. What is the value of this expression?
let x = 5 in x == 5
False
True
5
14. Which one of the following expressions should always evaluate to True?
"haskell" <> "python"
"haskell" < "python"
haskell < python
15. What’s wrong with the following Haskell expression?
if (1) then "true" else "false"
The condition is incorrectly typed, since it is an integer value
An endif statement is needed to show the end of the conditional expression
There should not be any brackets around the condition
16. Which one of the following expressions does not evaluate to 42?
head (zip [42] [True])
(*) 21 2
[7,23,42] !! ((+) 1 1)
17. Given these definitions:
a = "england" b = "scotland"
then which one of the following expressions has the greatest integer value?
length (zip a b)
length (zip b b)
length (zip a a)
18. What is wrong with this line of code, to return the number of characters typed by a user?
let x = getLine in length(x)
Because getLine is a function, it needs arguments. There are no arguments given in this code.
the code loops for ever
nothing is wrong — the code should work fine
The code associates the name x with the getLine function, rather than receiving a line of input from the user — and we can’t take length of a function.
19. What is the type of this function?
f name = putStrLn ("hello " ++ name)
[Char] -> IO ()
[Char] -> ()
IO [Char]
20. How do you find the type of a defined function f in ghci?
:type f
:load f
:show f
21. What is the difference between
->
and
<-
in Haskell syntax?
<-
indicates less than, whereas
->
indicates greater than
<-
is for associating names with values in do blocks whereas
->
is used for defining functions.
they are both two ways of representing the same thing.
22. Why do you think the generation and use of pseudo-random numbers might occur inside a monad?
because it is an interaction with ‘the outside world’
because the sequence of pseudo-random numbers is important, and the programmer needs to control it.
because it is defined in the Haskell Prelude library
23. A recursive function must have at least two cases. What are these called?
base case and general case
general case and specific case
base case and induction case
24. What is wrong with the following definition of filter?
filter :: (a -> Bool) -> [a] -> [a] filter pred [] = [] filter pred (x:xs) | pred x = x : filter pred xs | otherwise = filter pred (x:xs)
The base case is wrong
The predicate should operate on xs, not on x
The recursion for the matching case should work on (x:xs), not on xs
The recursion for the non-matching case should operate on xs, not on (x:xs)
25. What is the effect of the following fold?
foldl (\acc elt -> acc++[elt]) "" "A string"
It will return the string except its last character
It will return “gnirts Aâ€
It will return “A stringâ€
26. What is the wrong with the following map/fold-based computation?
foldl (+) (map (*2) [1..8])
The map and foldl functions should be swapped
foldl needs an accumulator argument.
map should take a function like (*), not (*2)
27. What is the result of the following computation?
foldr (/) 1 [2,4,8]
0.25
4.0
0.5
2.0
28. What is the result of the following computation?
foldl (/) 16 [8,4,2,1]
0.5
0.25
4.0
2.0
29.
let x = y + 2 y = x/3 in x+y
This code defines a pair of simultaneous equations. Will this work in Haskell?
yes — it will compute the two values that have mutually recursive definitions
no — it will either fail with an error or loop forever.
30. How do we generate an infinite list of integer 1 values?
take 1
[1..1]
repeat 1
[1..]
31. What is the missing case clause in the following definition of a function to calculate the length of a Haskell list?
mylength l = case l of -- MISSING CLAUSE -- x:xs -> 1+mylength xs
[] <- 0
[] -> 0
Null -> 0
32. In a Haskell guard expression, each of the guards evaluates to a Bool value, either True or False. What is the Bool value for the otherwise case?
Maybe True
True
False
33. Select which one of the following two let expressions will evaluate to the String
"prime minister"
let x = numeral ++ " minister" where numeral = "prime" in x
let x = numeral ++ " minister" in x where numeral = "prime"
34. Study the Haskell function f below. What does f() evaluate to?
f :: () -> String f () = let x = (Just Nothing) in case x of (Just _) -> "something" Nothing -> "nothing"
"something"
Nothing
"nothing"
35. Which one of the following functions will not loop infinitely, if we evaluate it in ghci?
take 10 [1..]
length [1..]
tail [1..]
36. Given a Tree data type as defined earlier in the course:
data Tree = Leaf | Node Int Tree Tree deriving Show
with Leaf and Node constructors, then how do we define an infinite tree?
mkInfiniteTree = Node 0 (mkInfiniteTree) (mkInfiniteTree)
mkInfiniteTree = Node 0 (mkInfiniteTree) (mkInfiniteTree)
mkInfiniteTree = mkInfiniteTree Node 0
37. Which one of the following expressions generates an infinite list of successive factorial numbers? (Recall that the nth factorial is the product of the first n positive integers.)
facts = [1,2,6,...]
facts = map (\x-> (foldr (*) 1 [1..x])) [1..]
facts = (*) [1..]
38. Does the following expression terminate?
let bot = bot bottomList = repeat bot in length(take 5 bottomList)
yes, returning integer value 5
no, it loops forever
39. What is the type of the
head
function?
head :: a -> a
head :: [a] -> a
head :: a -> Int
head :: [a] -> Int
40. What is the type of the
putStrLn
function?
putStrLn :: String -> IO ()
putStrLn :: String -> ()
putStrLn :: Char -> IO ()
putStrLn :: Show a => a -> IO ()
41. Given the following type declarations:
f :: T1 -> T2 g :: T2 -> T3
And given that the following expression typechecks:
v :: T1 v = h f g
What is the type of h?
h :: T3 -> T2 -> T1
h :: T1 -> T2 -> T3
h :: (T1 -> T2) -> (T2 -> T3) -> T1
h :: (T3 -> T2) -> (T2 -> T1) -> T3
42. What is the type of the following function:
\f -> f f
True
It is not possible to type this expression correctly in Haskell
Bottom
43. Complete the following type definition to define a binary tree with the values stored only in the leaf nodes:
data Tree a = Node __ __ | Leaf __
data Tree a = Node Tree Tree | Leaf
data Tree a = Node a a | Leaf
data Tree a = Node Leaf Leaf | Leaf (Tree a)
data Tree a = Node (Tree a) (Tree a) | Leaf a
44. What is the type of the following function (use a,b,c etc as type variables in order of occurence):
\x y -> y
\x y -> y :: a -> b -> b
\x y -> y :: a -> a -> b
\x y -> y :: a -> a -> a
\x y -> y :: a -> b -> c
45. Is the following expression correctly typed?
sq :: Int -> Float sq x = x*x
Yes
No
46. Is the following expression correctly typed?
join :: String -> [String] -> String join str strs = foldl (++) str strs
Yes
No
47. What is the result of evaluation of the following expression?
(\x y -> x*x-y*y) 3 4
-20
-7
20
7
48. What is the result of evaluating the following expression?
map (\x -> length x) ["This","is", "a","test"]
an error
4
[4,2,1,4]
49. What is the result of evaluating the following expression?
(\x -> (\y -> y x)) "x" (\y -> y)
(\y -> y x) "x"
"x"
an error
(\x -> (\y -> y x)) "x"
50. What is the result of evaluating the following expression?
(\x -> (\y -> x y)) "x"
a partially applied function
a type error
a string value
51. What is the result of evaluating the following expression?
(\x f -> f x) 4 (\x -> x*x)
a partially applied function
4
16
52. What is the result of evaluating the following expression?
(\x -> 1) 2
1
2
a type error
This quiz is about the Parser parser combinator library. You will be asked to complete some code for each question. First study the code below in detail. It provides the data type for a parser of the JSON format used in JavaScript.
module JSONTypes ( JValue(..), mkJPair, mkJObj ) where import Data.Map hiding ( map ) type JMap = Data.Map.Map String JValue data JValue = JString String | JNumber Integer | JObject JMap | JArray [JValue] | JBool Bool | JNull deriving (Show) mkJPair k v = JObject (Data.Map.singleton k v) mkJObj :: [JValue] -> JValue mkJObj j_vals = let list_of_maps = map (\(JObject pair) -> pair) j_vals combined_map = Data.Map.unions list_of_maps in JObject combined_map
53. What is the type of the function json_parser?
json_parser :: Parser __ json_parser = do whiteSpace j_top <- ( json_array_parser <|> json_obj_parser) return j_top
json_parser :: Parser JValue
54. A JSON array consists of a comma-separated list of JSON values enclosed by braces, e.g.
[ 1, 'two', [ 3, true] ]
To parse this format we use the function json_array_parser below. What is the correct data constructor for the return value?
json_array_parser :: Parser JValue json_array_parser = do j_vals <- brackets $ commaSep json_value_parser return $ __ j_vals
return $ JArray j_vals
55. The JSON format supports boolean values, named true and false.
In the boolean JSON value parser below, what is the missing combinator?
json_bool_parser = do bstr <- ( symbol "true" __ symbol "false" ) let bval = if bstr == "true" then True else False return $ JBool bval
( symbol "true" <|> symbol "false" )
56. A JSON object is a list of key-value pairs, where the key is a string and the value a JSON value, enclosed in braces, e.g.
{ "Street" : "Lilybank Gardens", "Nr" : 18, "Org" : [ "University of Glasgow", { "School" : "Computing Science"} ] }
The most general JValue parser is json_value_parser, which is built of parsers for specific JSON values:
json_value_parser = json_array_parser <|> json_obj_parser <|> json_string_parser <|> json_number_parser <|> json_bool_parser <|> json_null_parser
In the JSON pair parser below, provide the name of the parser for the ‘value’ part of the pair
json_pair_parser = do k <- stringLiteral colon v <- __ return $ mkJPair k v
v <- json_value_parser
57. In the JSON object parser below, complete the return expression.
json_obj_parser :: Parser JValue json_obj_parser = do j_vals <- braces $ commaSep json_pair_parser -- a list of pairs return $ __ j_vals
return $ mkJObj j_vals
58. Given the following parser:
yin_yang :: Parser String yin_yang = do xs <- string "yin" <|> string "yang" return xs
With the definition as above this parser will fail when trying to parse “yangâ€:
*Main> run yin_yang "yang" parse error at (line 1, column 1): unexpected "a" expecting "yin"
How should you modify the parser so that it will work correctly?
yin_yang :: Parser String yin_yang = do xs <- string "yin" <|> try (string "yang") return xs
yin_yang :: Parser String yin_yang = do xs <- try (string "yin") <|> string "yang" return xs
yin_yang :: Parser String yin_yang = do xs <- try (string "yin" <|> string "yang") return xs
Submit Quiz