Seven Languages in Seven Weeks: Haskell Day 1 & 2

For the Haskell questions, I have included all the answers in a single file, one file per day. I have put the question numbers in the comments.

Here were the questions for the first day:

module Main where
	-- question 1 a
	allEven :: [Integer] -> [Integer]
	allEven [] = []
	allEven (h:t) = if even h then h:allEven t else allEven t
	
	-- question 1 b
	allEven2 :: [Integer] -> [Integer]
	allEven2 list = [x | x <- list, even x]
	
	-- question 2 
	reverseList :: [a] -> [a]
	reverseList [] = []
	reverseList (head:tail) = reverseList tail ++ [head] 

	-- question 3
	colors = ["black", "blue", "white", "yellow", "red"]
	allColors = [(a, b) | a <- colors, b <- colors, a < b]
	
	-- question 4
	multTable :: Integer -> [(Integer, Integer, Integer)]
	multTable x = [(a, x, a * x) | a <- [1..12]]
	
	-- question 5
	mapColors = ["blue", "green", "red"]
	mapColoring = [(("Tennessee", a), ("Mississippi", b), ("Alabama", c), ("Georgia", d), ("Florida", e)) 
												  | a <- mapColors, 
													b <- mapColors, 
													c <- mapColors, 
													d <- mapColors, 
													e <- mapColors,
													a /= b, a /=c, a /= d,
													b /= c,
													c /= d, c /= e,
													d /= e
													]

Again, like for day one, I have included all my answers in a single file, with comments specifying the question numbers.

module Main where
	-- question 1
	sort :: [Integer] -> [Integer]
	sort [] = []
	sort list = [minimum list] ++ sort [x | x <- list, x /= minimum list]
	
	-- question 2
	sortWith [] f = []
	sortWith list f = [f list] ++ sortWith [x | x <- list, x /= f list] f
	
	-- question 4
	everyThird x = x:(everyThird (x + 3))
	everyFifth y = y:(everyFifth (y + 5))
	everyEigth x y = zipWith (+) (everyThird x) (everyFifth y)
	
	-- question 5
	prod a b = a * b
	halfOf = prod 0.5  

	-- question 6
	appendToString s a = a ++ s
	addNewLine = appendToString "\n"
	
	-- bonus question 1
	biggestCommonDenominator :: Integer -> Integer -> Integer 
	biggestCommonDenominator a 0 = a
	biggestCommonDenominator a b = biggestCommonDenominator b (mod a b)

2 thoughts on “Seven Languages in Seven Weeks: Haskell Day 1 & 2

  1. Tu m’a convaincu d’acheter le livre … pis j’ai pas le temps de lire ça! Vais encore couper sur mes nuits. Ma blonde va m’haïr, elle va me dumper! Mes enfants vont faire des dépressions et manquer leurs études! Ils vont se ramasser dans la rue à quêter pis ça va être de ta faute!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s