List comprehensions -require base case? - haskell

I don't understand why the base case is needed in this:
-- perms :: Ord a => [a] -> [[a]]
perms [] = [[]]
perms xs = [ (x:ps) | x <- xs, ps <- perms (xs \\ [x])]
It seems to me that it should be automatic from the list-comprehension, but then I noticed that:
[ x:y | x<-[], y<-[] ]
evaluates to [], and not [[]], which seems surprising.
Even so, I was also surprised that without the base case it runs, but always gives [], which violates the type signature.
Is there an easy way to trace the execution of a list comprehension? It seems atomic to Debug.Trace.trace.

You can think of <- as use every element from the list in right in the expression in left.
Since [] has no elements the whole list comprehension returns an empty list.
It will be strange if [ x:y | x<-[], y<-[] ] returns [[]] because : takes element and a list. So to generate [[]] y must be [] but then what will be x?
As KennyTM said [] is of type [[a]]. Actually [] is from every type of this kind:
[a] [[a]] [[[a]]] and so on. If it wasn't then there is no way a function to return an empty list.
Anyway it is a very common mistake to forget some brackets and this is why type annotations are necessary.

Let's de-sugar!
[ x:y | x <- [], y <- [] ]
Turns into
do x <- []
y <- []
return (x:y)
Now, more de-sugaring! Yay!
[] >>= \x -> ([] >>= \y -> return (x:y))
iirc, >>= for lists is flip concatMap, and return is simply \x -> [x]
Let's only do a little bit of that replacement.
concatMap (\x -> ([] >>= \y -> return (x:y))) []
There, now do you see? concatMap f [] will obviously evaluate to []. Because concatMap f is just concat . map f. So map f onto the empty list, and then concatenate the results. Except there are no results, so the final evaluation is [].

So it comes down to the meaning of
[ x:y | x<-[], y<-[] ]
The way to read this is, "What are the possible values of x:y, when x has no possible values, and y has no possible values?" Hopefully, it should be clear that in that case, there are no values at all for x:y, since you'd need a value for x and a value for y to get a possibility for x:y, and you have neither.
This general pattern of selecting combinations of possible values for x and y is called a cartesian product, and the word "product" is used in part because the number of possibile combinations is equal to the number of possibilities for x, times the number of possibilities for y. So if there are zero choices for x, and zero choices for y, you can expect 0 * 0 = 0 choices for combinations of the two.

Here's another hint why there is a base case with an empty list. How many permutations are there of n elements? There are n! permutations. And what is 0!? It's 1. So the length of the result list for perm [] has to be 1. The types and the lack of elements of type a forces the result to be [[]]. No other defined value has the right type and length.

If you have a list comprehension of the form:
[ x:y | stuff ]
then you are producing a list whose elements are of the form x:y for some choices of x and y as determined by stuff. [[]] is a list whose elements are not of the form x:y for any x or y, so the former cannot produce the latter.
In expecting [[]] from [ x:y | x <- [], y <- [] ], you seem to be setting x = [] and y = [] and then considering x:y = [[]]. This is wrong for a couple of reasons:
x is coming from xs of type [a], so x has type a, and is not (in general) a list
the result of the list comprehension is a list of x:y elements, not a single one.

Related

How do you compute all combinations of lists within a list in Haskell?

As the questions states, I have a multi-dimensional list and I want to compute a list, with all possible combinations of those lists.
I only have a functions for one dimensional lists, which looks like this:
combinations :: [a] -> [[a]]
combinations xs = [ [x,y] | x <- xs, y <- xs]
The desired output for multi-dimensional lists would look like this: combinationsM [[1,2],[3,4]] = [[[1,2],[3,4]],[[3,4],[1,2]]]
Your combinations function handles a list of lists of elements. It simply sees a list, and the items of these lists are lists, but the function does not care about this. For [[1,2], [3,4]] it will thus return:
ghci> combinations [[1,2], [3,4]]
[[[1,2],[1,2]],[[1,2],[3,4]],[[3,4],[1,2]],[[3,4],[3,4]]]
It thus has as combinations two times [1,2], a [1,2] and [3,4], a [3,4] and [1,2], and two times [3,4].
Your function thus already returns combinations of sublists. It simply works with lists of any type.
If you want to remove combinations where you pick the same sublist twice, you can define a helper that picks an element and also returns the list of the remaining elements:
pick :: [a] -> [(a, [a])]
pick [] = []
pick (x:xs) = (x, xs) : map … …
where the … parts are left as an exercise. The function should make a recursive call, and prepend all the lists with x in the map … … part.
This thus means that pick [1,4,2,5] returns [(1, [4,2,5]), (2, [1,4,5]), (4, [1,2,5]), (5, [1,4,2])].
Then we can obtain the combinations without picking the same element twice with:
combinations :: [a] -> [[a]]
combinations xs = [[x, y] | (x, ys) <- pick xs, y <- ys]
It might also be better to return a list of 2-tuples, this adds more context to the return type, since then we know it is impossible that a combination contains a different number of items than 2:
combinations :: [a] -> [[a]]
combinations xs = [(x, y) | (x, ys) <- pick xs, y <- ys]

Take symmetrical pairs, of different numbers from list

I have a list like this:
[(2,3),(2,5),(2,7),(3,2),(3,4),(3,6),(4,3),(4,5),(4,7),(5,2),(5,4),(5,6),(6,3),(6,5),(6,7),(7,2),(7,4),(7,6)]
The digits are from [2..7]. I want to take a set where there are any symmetrical pairs. e.g. [(1,2),(2,1)], but those two numbers aren't used again in the set. An example would be:
[(3,6),(6,3),(2,5),(5,2),(4,7),(7,4)]
I wanted to first put symmetric pairs together as I thought it might be easier to work with so i created this function, which actually creates the pairs and puts them in another list
g xs = [ (y,x):(x,y):[] | (x,y) <- xs ]
with which the list turns to this:
[[(3,2),(2,3)],[(5,2),(2,5)],[(7,2),(2,7)],[(2,3),(3,2)],[(4,3),(3,4)],[(6,3),(3,6)],[(3,4),(4,3)],[(5,4),(4,5)],[(7,4),(4,7)],[(2,5),(5,2)],[(4,5),(5,4)],[(6,5),(5,6)],[(3,6),(6,3)],[(5,6),(6,5)],[(7,6),(6,7)],[(2,7),(7,2)],[(4,7),(7,4)],[(6,7),(7,6)]]
Then from here I was hoping to somehow remove duplicates.
I made a function that will look at all of the fst elements of all of the pairs:
flatList xss = [ x | xs <- xss, (x,y) <- xs ]
to use with another function to remove the duplicates.
h (x:xs) | (fst (head x)) `elem` (flatList xs) = h xs
| otherwise = (head x):(last x):(h xs)
which gives me the list
[(3,6),(6,3),(5,6),(6,5),(2,7),(7,2),(4,7),(7,4),(6,7),(7,6)]
which has duplicate numbers. That function only takes into account the first element of the first pair in the list of lists,the problem is when I also take into account the first element of the second pair (or the second element of the first pair):
h (x:xs) | (fst (head x)) `elem` (flatList xs) || (fst (last x)) `elem` (flatList xs) = h xs
| otherwise = (head x):(last x):(h xs)
I only get these two pairs:
[(6,7),(7,6)]
I see that the problem is that this method of deleting duplicates grabs the last repeated element, and would work with a list of digits, but not a list of pairs, as it misses pairs it needs to take.
Is there another way to solve this, or an alteration I could make?
It probably makes more sense to use a 2-tuple of 2-tuples in your list comprehension, since that makes it more easy to do pattern matching, and thus "by contract" enforces the fact that there are two items. We thus can construct 2-tuples that contain the 2-tuples with:
g :: Eq a => [(a, a)] -> [((a, a), (a, a))]
g xs = [ (t, s) | (t#(x,y):ts) <- tails xs, let s = (y, x), elem s ts ]
Here the elem s ts checks if the "swapped" 2-tuple occurs in the rest of the list.
Then we still need to filter the elements. We can make use of a function that uses an accumulator for the thus far obtained items:
h :: Eq a => [((a, a), (a, a))] -> [(a, a)]
h = go []
where go _ [] = []
go seen ((t#(x, y), s):xs)
| notElem x seen && notElem y seen = t : s : go (x:y:seen) xs
| otherwise = go seen xs
For the given sample input, we thus get:
Prelude Data.List> (h . g) [(2,3),(2,5),(2,7),(3,2),(3,4),(3,6),(4,3),(4,5),(4,7),(5,2),(5,4),(5,6),(6,3),(6,5),(6,7),(7,2),(7,4),(7,6)]
[(2,3),(3,2),(4,5),(5,4),(6,7),(7,6)]
after reading a few times your question, I got an elegant solution to your problem. Thinking that if you have a list of pairs without any repeated number, you can get the list of swapped pairs easily, solving your problem. So your problem can be reduce to given a list, get the list of all pairs using each number just one.
For a given list, there are many solutions to this, ex: for [1,2,3,4] valid solutions are: [(2,4),(4,2),(1,3),(3,1)] and [(2,3),(3,2),(1,4),(4,1)], etc... The approach here is:
take a permutation if the original list (say [1,4,3,2])
pick one element for each half and pair them together (for simplicity, you can pick consecutive elements too)
for each pair, create a the swapped pair and put all together
By doing so you end up with a list of non repeating numbers of pairs and its symmetric. More over, looping around all permutaitons, you can get all the solutions to your problem.
import Data.List (permutations, splitAt)
import Data.Tuple (swap)
-- This function splits a list by the half of the length
splitHalf :: [a] -> ([a], [a])
splitHalf xs = splitAt (length xs `quot` 2) xs
-- This zip a pair of list into a list of pairs
zipHalfs :: ([a], [a]) -> [(a,a)]
zipHalfs (xs, ys) = zip xs ys
-- Given a list of tuples, creates a larger list with all tuples and all swapped tuples
makeSymetrics :: [(a,a)] -> [(a,a)]
makeSymetrics xs = foldr (\t l -> t:(swap t):l) [] xs
-- This chain all of the above.
-- Take all permutations of xs >>> for each permutations >>> split it in two >>> zip the result >>> make swapped pairs
getPairs :: [a] -> [[(a,a)]]
getPairs xs = map (makeSymetrics . zipHalfs . splitHalf) $ permutations xs
>>> getPairs [1,2,3,4]
[[(1,3),(3,1),(2,4),(4,2)],[(2,3),(3,2),(1,4),(4,1)] ....

How do i "put a restriction" on a list of permutations and subsequences of a list?

I'm really new to programming and Haskell in particular (so new that I actually don't know if this is a stupid question or not). But I was watching the lecture given by Eric Meijer (http://channel9.msdn.com/Series/C9-Lectures-Erik-Meijer-Functional-Programming-Fundamentals) and i was fascinated by the program written by Dr. Graham Hutton in lecture 11; The countdown problem.
My question is:
Is there a way of "filtering" the list of solutions by the length (number of elements), so that the list of solutions are restricted to the solutions that only uses (for example) three of the source numbers? In other words, I would like to change the question from "given the numbers [1,2,3,4,5,6,8,9] construct 18 using the operators..." to "given the numbers [..] which three numbers can be used to construct..."
In my futile attempts, I've been trying to put a kind restriction on his function subbags (which returns all permutations and subsequences of a list)
subbags :: [a] -> [[a]]
subbags xs = [zs | ys <- subs xs, zs <- perms ys]
So that I get all the permutations and subsequences that only contain three of the source numbers. Is this possible? If so, how?
Like I said, I have no idea if this is even a legitimate question - but I have gone from curious to obsessed, so any form of help or hint would be greatly appreciated!
The simplest way would be to just select from the candidates three times
[ (x, y, z) | x <- xs, y <- xs, z <- xs ]
although this assumes that repeat use of a single number is OK.
If it's not, we'll have to get smarter. In a simpler scenario we'd like to pick just two candidates:
[ (x, y) | x <- xs, y <- ys, aboveDiagonal (x, y) ]
in other words, if we think of this as a cartesian product turning a list into a grid of possibilities, we'd like to only consider the values "above the diagonal", where repeats don't happen. We can express this by zipping the coordinates along with the values
[ (x, y) | (i, x) <- zip [1..] xs
, (j, y) <- zip [1..] xs
, i < j
]
which can be extended back out to the n=3 scenario
[ (x, y, z) | (i, x) <- zip [1..] xs
, (j, y) <- zip [1..] xs
, (k, z) <- zip [1..] xs
, i < j
, j < k
]
Ultimately, however, this method is inefficient since it still has to scan through all of the possible pairs and then prune the repeats. We can be a bit smarter by only enumerating the above diagonal values to begin with. Returning to n=2 we'll write this as
choose2 :: [a] -> [(a, a)]
choose2 [] = []
choose2 (a:as) = map (a,) as ++ choose2 as
In other words, we pick first all of the pairs where the head of the list comes first and a value in the tail of the list comes second—this captures one edge of the upper triangle—and then we recurse by adding all of the upper diagonal values of the list of candidates sans the head.
This method can be straightforwardly extended to the n=3 case by using the n=2 case as a building block
choose3 :: [a] -> [(a, a, a)]
choose3 [] = []
choose3 (a:as) = map (\(y, z) -> (a, y, z)) (choose2 as) ++ choose3 as
which also provides a direct generalization to the fully general n dimensional solution
choose :: Int -> [a] -> [[a]]
choose 0 as = [[]] -- there's one way to choose 0 elements
choose _ [] = [] -- there are 0 ways to choose (n>0) elements of none
choose 1 as = map (:[]) as -- there are n ways to choose 1 element of n
choose n (a:as) = map (a:) (choose (n-1) as) ++ choose n as
I like this solution, which does not require the list elements to be an instance of Eq:
import Data.List (tails)
triples ls = [[x,y,z] | (x:xs) <- tails ls,
(y:ys) <- tails xs,
z <- ys]
This returns only subsequences, not permutations, though.

Swapping Pairs in Haskell

So i've got this function to swap pairs of numbers in haskell, and i don't know what i've done wrong, maybe you guys can give me a hand.
SO basically this function gets a list, say, [1,2,3,4,5], and returns the numbers swapped by pairs, something like, [2,1,4,3,5]. if the number of elements is odd, the last element stays the same.
Here's what i've done:
swapPairs :: [a] -> [a]
swapPairs (x:xs) = [!!x = !!x+1 && !!x+1 = !!x| x <- xs]
-- Return first two elements in inverted order, recusively call for remaining list,
-- only matches lists of two or more elements
swapPairs (a:b:xs) = b : a : swapPairs xs
-- Return tail for zero or one remaining elements
swapPairs (xs) = xs
You can use pattern matching to fetch 2 head elements:
swapPairs (x:y:xs) = y : x : (swapPairs xs)

Breaking down a haskell function

I'm reading Real world haskell book again and it's making more sense. I've come accross this function and wanted to know if my interpretation of what it's doing is correct. The function is
oddList :: [Int] -> [Int]
oddList (x:xs) | odd x = x : oddList xs
| otherwise = oddList xs
oddList _ = []
I've read that as
Define the function oddList which accepts a list of ints and returns a list of ints.
Pattern matching: when the parameter is a list.
Take the first item, binding it to x, leaving the remainder elements in xs.
If x is an odd number prepend x to the result of applying oddList to the remaining elements xs and return that result. Repeat...
When x isn't odd, just return the result of applying oddList to xs
In all other cases return an empty list.
1) Is that a suitable/correct way of reading that?
2) Even though I think I understand it, I'm not convinced I've got the (x:xs) bit down. How should that be read, what's it actually doing?
3) Is the |...| otherwise syntax similar/same as the case expr of syntax
1 I'd make only 2 changes to your description:
when the parameter is a nonempty list.
f x is an odd number prepend x to the result of applying oddList to the remaining elements xs and return that result. [delete "Repeat...""]
Note that for the "_", "In all other cases" actually means "When the argument is an empty list", since that is the only other case.
2 The (x:xs) is a pattern that introduces two variables. The pattern matches non empty lists and binds the x variable to the first item (head) of the list and binds xs to the remainder (tail) of the list.
3 Yes. An equivalent way to write the same function is
oddList :: [Int] -> [Int]
oddList ys = case ys of { (x:xs) | odd x -> x : oddList xs ;
(x:xs) | otherwise -> oddList xs ;
_ -> [] }
Note that otherwise is just the same as True, so | otherwise could be omitted here.
You got it right.
The (x:xs) parts says: If the list contains at least one element, bind the first element to x, and the rest of the list to xs
The code could also be written as
oddList :: [Int] -> [Int]
oddList (x:xs) = case (odd x) of
True -> x : oddList xs
False -> oddList xs
oddList _ = []
In this specific case, the guard (|) is just a prettier way to write that down. Note that otherwise is just a synonym for True , which usually makes the code easier to read.
What #DanielWagner is pointing out, is we in some cases, the use of guards allow for some more complex behavior.
Consider this function (which is only relevant for illustrating the principle)
funnyList :: [Int] -> [Int]
funnyList (x1:x2:xs)
| even x1 && even x2 = x1 : funnyList xs
| odd x1 && odd x2 = x2 : funnyList xs
funnyList (x:xs)
| odd x = x : funnyList xs
funnyList _ = []
This function will go though these clauses until one of them is true:
If there are at least two elements (x1 and x2) and they are both even, then the result is:
adding the first element (x1) to the result of processing the rest of the list (not including x1 or x2)
If there are at least one element in the list (x), and it is odd, then the result is:
adding the first element (x) to the result of processing the rest of the list (not including x)
No matter what the list looks like, the result is:
an empty list []
thus funnyList [1,3,4,5] == [1,3] and funnyList [1,2,4,5,6] == [1,2,5]
You should also checkout the free online book Learn You a Haskell for Great Good
You've correctly understood what it does on the low level.
However, with some experience you should be able to interpret it in the "big picture" right away: when you have two cases (x:xs) and _, and xs only turns up again as an argument to the function again, it means this is a list consumer. In fact, such a function is always equivalent to a foldr. Your function has the form
oddList' (x:xs) = g x $ oddList' xs
oddList' [] = q
with
g :: Int -> [Int] -> [Int]
g x qs | odd x = x : qs
| otherwise = qs
q = [] :: [Int]
The definition can thus be compacted to oddList' = foldr g q.
While you may right now not be more comfortable with a fold than with explicit recursion, it's actually much simpler to read once you've seen it a few times.
Actually of course, the example can be done even simpler: oddList'' = filter odd.
Read (x:xs) as: a list that was constructed with an expression of the form (x:xs)
And then, make sure you understand that every non-empty list must have been constructed with the (:) constructor.
This is apparent when you consider that the list type has just 2 constructors: [] construct the empty list, while (a:xs) constructs the list whose head is a and whose tail is xs.
You need also to mentally de-sugar expressions like
[a,b,c] = a : b : c : []
and
"foo" = 'f' : 'o' : 'o' : []
This syntactic sugar is the only difference between lists and other types like Maybe, Either or your own types. For example, when you write
foo (Just x) = ....
foo Nothing = .....
we are also considering the two base cases for Maybe:
it has been constructed with Just
it has been constructed with Nothing

Resources