Problems 1

Basic Expressions and Functions

  1. Give the type and value of each of the following expressions. For example, given the expression 2+2, the answer should be written as 4 :: Int. Note, some expressions may be errors.

  1. Given the following definition of the function f, simplify the expression f (f 1 2) (f 3 4), showing all your steps.

f :: Int -> Int -> Int

f x y = 2*x + 3

f (f 1 2) (f 3 4) => f (2*1+3) (f 3 4) => f 5 (f 3 4) => f 5 (2*3 + 3) => f 5 9 => 2*5 + 3=>13

  1. Write a function isLetter :: Char -> Bool that determines whether its argument is a letter of the alphabet.
  2. isletter x = (x>='A' && x<= 'Z') || (x>='a' && x<= 'z')
  3. Write a function capitalise :: String -> String that makes all the letters upper case.
  4. capitalise xs = map toUpper xs

  5. Write a function that determines whether or not one string is the prefix of another string.
  6. prefix [] ys = True

    prefix xs [] = False

    prefix (x:xs) (y:ys) = if (x==y) then prefix xs ys else False

    or

    prefix xs ys = (xs == take (length xs) ys)

  7. Write a function that occurs :: Int -> [Int] -> Int that returns the number of times a given number occurs in a list.
  8. occurs x xs = sum [1|y<-xs, y == x]

  9. Write a function reverse that reverses a string.
  10. reverse1 [] = []

    reverse1 (x:xs) = (reverse1 xs) ++ [x]

    or

    reverse2 [] = []

    reverse2 xs = rev (xs,[])

    where

    rev ([],ys) = ys

    rev (x:xs,ys) = rev (xs, (x:ys))

  11. Write a function palindrome :: String -> Bool that determines whether its argument is a palindrome. A palindrome is a string which is the same when you reverse it; for example, ‘abccba’ is a palindrome, but ‘abcca’ is not.

palindrome xs = xs == (reverse1 xs)