HomeWork I

Fun with Haskell

stringSum :: String -> Int

-- examples
stringSum "1 1"       == 2
stringSum "100\n\t-3" == 97

Task 1: sum of all numbers in string

tests = [ "1", "1 2 3", " 1", "1 ", "\t1\t", "\t12345\t", "010 020 030"
        , " 123 456 789 ", "-1", "-1 -2 -3", "\t-12345\t", " -123 -456 -789 "
        , "\n1\t\n3   555  -1\n\n\n-5", "123\t\n\t\n\t\n321 -4 -40"
        ]

mustFail = ["asd", "1-1", "1.2", "--2", "+1", "1+"]

Tests

Advanced version: support unary plus

advancedTests    = [ "+1", "1 +1", "-1 +1", "+1 -1"]
advancedMustFail = ["1+1", "++1", "-+1", "+-1", "1 + 1"]
ghci> zipN sum [ [1, 2, 3] 
               , [4, 5, 6] 
               , [7, 8, 9]]
[12,15,18]

Task 2: zipN

Usage

Advanced version: zipN must be lazy and work with infinite lists if given function is lazy

Implement zipN function

ghci> take 5 $ zipN (take 3) $ repeat [0..]
[[0,0,0],[1,1,1],[2,2,2],[3,3,3],[4,4,4]]

ghci> take 5 $ zipN (take 3) $ repeat [0..1]
[[0,0,0],[1,1,1]]

Task 3: merge sort

mergeSort :: [Int] -> [Int]

mergeSort [2, 1, 0, 3, 10, 5] = [0, 1, 2, 3, 5, 10]
import           System.Random (newStdGen, randomRs)

randomIntList :: Int -> Int -> Int -> IO [Int]
randomIntList n from to = take n . randomRs (from, to) <$> newStdGen

Paste this in the top of your file to test on random lists

ghci> example <- randomIntList 5 (-10) 10
ghci> example
[-8,1,-8,-5,-7]
ghci> mergeSort example
[-8,-8,-7,-5,1]

Usage

Copy of Homework 1

By Eugene Nemchenko

Copy of Homework 1

Simple homework on basic Haskell syntax

  • 37