Being able to manipulate lists is really important in any language.
Haskell isn’t as difficult as it may seem at first.
I think the majority of negativity towards this language comes from adjusting to it being a declarative language, not an object-oriented one.
Squaring All Integers in a Given Range (Single Generator)
You don’t need a function to do this. You can run this directly from your GHCi command screen.
[ x^2 | x <- [1..10] ] more or less translates to “x to the power of 2, for all x in the range 1 to 10.
x <- [1..10] part is the generator. It generates values for x.
List Of Ordered Pairs (2 Generators)
[ (x,y) | x <- [1,2,3,4,5], y <- ["a","b","c"] ] uses two generators.
One for x, one for y; each has their own list.
It will return all combinations.
Joining a List of Lists (Dependant Generators)
-- this program will join a list of lists demoList = [[1,2,3],[4,5],[6,7]] -- just a preset list of lists joinLists :: [[a]] -> [a] -- takes in some list of lists containing some polymorphic type joinLists xss = [ x | xs <- xss, x <- xs ] -- for x in each xs from xss, x
You’ll notice in this function, the command
[ x | xs <- xss, x <- xs ] is used.
This can be understood simply as:
- a list containing “x”s
- where the “xs”s are pulled from the input “xss”
- and the “x”s are pulled from the “xs”s
This uses a dependant generator in that, we cannot get to
x <- xs without getting
xs <- xss first.
Get All Even Numbers in a Given Range (Uses a Guard)
If we want to find all even numbers in a given range we can do that. We’ll be using a generator of
x , [1..n] which gives us a list of all numbers from 1 to
n the input. However, we want to guard against the odd numbers, so we need to use
x mod 2 == 0 so we’re only given numbers that divide by
2 and leave a remainder of
allEvenUpto :: Integer -> [Integer] allEvenUpto n = [ x | x <- [1..n], x `mod` 2 == 0 ]
The generator is guarded in this case by
x mod 2 == 0.
Only when the guard is true, is the
x generated and put into the list for returning.
Get List of Factors for a Given Number
This program is very similar to the “all even in range” example. We’re generating all x between 1 and (input) n, where
n mod x is equal to 0.
mod part is useful for determining whether something divides into something. If
n mod x == 0 then it must be a factor. For example,
2 mod 4 would equal 0. However,
2 mod 5 would be equal to
1 because there is
1 remaining after the division.
getFactors :: Integer -> [Integer] getFactors n = [ x | x <- [1..n], n `mod` x == 0 ]
This program works really well for this purpose. It returns the list of all factors for the given input
You can see in the above example that for each of the numbers
[1,2,5,10] they are a factor of