Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Informatics 1 - Functional Programming
- -- Tutorial 2
- --
- -- Week 4 - due: 13/14 Oct.
- import Data.Char
- import Data.List
- import Test.QuickCheck
- -- 1.
- rotate :: Int -> [Char] -> [Char]
- rotate n [] = error "Cannot rotate empty list"
- rotate n xs |n < length xs && n > 0 = drop n xs ++ take n xs
- |n <= 0 = error "You cannot rotate a string by 0 or by a negative number."
- |n >= length xs = error "n cannot be bigger than your string."
- -- 2.
- -- (b) It takes the modulus of the number by the length of the string
- -- if it is too large or negative it will return 0, which will end
- -- in doing rotate l str == str which is true.
- prop_rotate :: Int -> String -> Bool
- prop_rotate k str = rotate (l - m) (rotate m str) == str
- where l = length str
- m = if l == 0 then 0 else k `mod` l
- -- 3.
- makeKey :: Int -> [(Char, Char)]
- makeKey n = zip ['A'..'Z'] (rotate n ['A'..'Z'])
- -- 4.
- -- unzip the 2 lists, try if k is equal to the first term of my list
- -- if not drop the first
- lookUp :: Char -> [(Char, Char)] -> Char
- lookUp c [] = c
- lookUp c ((x,y):xs) | c==x = y
- | c/=x = lookUp c xs
- -- 5.
- encipher :: Int -> Char -> Char
- encipher n c = lookUp c (makeKey n)
- -- 6.
- normalize :: String -> String
- normalize (xs) = [toUpper x | x <- xs, isAlpha x || isDigit x]
- -- 7
- encipherStr :: Int -> String -> String
- encipherStr n [] = []
- encipherStr n (xs) = [encipher n x | x <- (normalize (xs))]
- -- 8.
- reverseKey :: [(Char, Char)] -> [(Char, Char)]
- reverseKey [] = []
- reverseKey ((x,y):xs) = (y,x) : reverseKey (xs)
- -- 9.
- decipher :: Int -> Char -> Char
- decipher n c = lookUp c (reverseKey(makeKey n))
- decipherStr :: Int -> String -> String
- decipherStr n [] = []
- decipherStr n (x:xs) = decipher n x : decipherStr n xs
- -- 10.
- prop_cipher :: Int -> String -> Property
- prop_cipher n xs = (n <= length xs && n > 0) ==> (normalize xs == decipherStr n(encipherStr n xs))
- -- 11.
- contains :: String -> String -> Bool
- contains xs [] = False
- contains [] ys = False
- contains (x:xs) ys |take (length ys) (x:xs) == ys = True
- |otherwise = contains xs ys
- -- 12.
- candidates :: String -> [(Int, String)]
- candidates xs = [(n, decipherStr n xs) | n <- [1..25], contains (decipherStr n xs) "THE" || contains (decipherStr n xs) "AND"]
Add Comment
Please, Sign In to add comment