Haskell: List combination for Integers - haskell

I have a given list, e.g. [2, 3, 5, 587] and I want to have a complete list of the combination. So want something like [2, 2*3,2*5, 2*587, 3, 3*5, 3*587, 5, 5*587, 587]. Since I am on beginner level with Haskell I am curious how a list manipulation would look like.
Additionally I am curious if the computation of the base list might be expensive how would this influence the costs of the function? (If I would assume the list has limit values, i.e < 20)
Rem.: The order of the list could be done afterwards, but I have really no clue if this is cheaper within the function or afterwards.

The others have explained how to make pairs, so I concern myself here with getting the combinations.
If you want the combinations of all lengths, that's just the power set of your list, and can be computed the following way:
powerset :: [a] -> [[a]]
powerset (x:xs) = let xs' = powerset xs in xs' ++ map (x:) xs'
powerset [] = [[]]
-- powerset [1, 2] === [[],[2],[1],[1,2]]
-- you can take the products:
-- map product $ powerset [1, 2] == [1, 2, 1, 2]
There's an alternative powerset implementation in Haskell that's considered sort of a classic:
import Control.Monad
powerset = filterM (const [True, False])
You could look at the source of filterM to see how it works essentially the same way as the other powerset above.
On the other hand, if you'd like to have all the combinations of a certain size, you could do the following:
combsOf :: Int -> [a] -> [[a]]
combsOf n _ | n < 1 = [[]]
combsOf n (x:xs) = combsOf n xs ++ map (x:) (combsOf (n - 1) xs)
combsOf _ _ = []
-- combsOf 2 [1, 2, 3] === [[2,3],[1,3],[1,2]]

So it seems what you want is all pairs of products from the list:
ghci> :m +Data.List
ghci> [ a * b | a:bs <- tails [2, 3, 5, 587], b <- bs ]
[6,10,1174,15,1761,2935]
But you also want the inital numbers:
ghci> [ a * b | a:bs <- tails [2, 3, 5, 587], b <- 1:bs ]
[2,6,10,1174,3,15,1761,5,2935,587]
This uses a list comprehension, but this could also be done with regular list operations:
ghci> concatMap (\a:bs -> a : map (a*) bs) . init $ tails [2, 3, 5, 587]
[2,6,10,1174,3,15,1761,5,2935,587]
The latter is a little easier to explain:
Data.List.tails produces all the suffixes of a list:
ghci> tails [2, 3, 5, 587]
[[2,3,5,587],[3,5,587],[5,587],[587],[]]
Prelude.init drops the last element from a list. Here I use it to drop the empty suffix, since processing that causes an error in the next step.
ghci> init [[2,3,5,587],[3,5,587],[5,587],[587],[]]
[[2,3,5,587],[3,5,587],[5,587],[587]]
ghci> init $ tails [2, 3, 5, 587]
[[2,3,5,587],[3,5,587],[5,587],[587]]
Prelude.concatMap runs a function over each element of a list, and combines the results into a flattened list. So
ghci> concatMap (\a -> replicate a a) [1,2,3]
[1, 2, 2, 3, 3, 3]
\(a:bs) -> a : map (a*) bs does a couple things.
I pattern match on my argument, asserting that it matches an list with at least one element (which is why I dropped the empty list with init) and stuffs the initial element into a and the later elements into bs.
This produces a list that has the same first element as the argument a:, but
Multiplies each of the later elements by a (map (a*) bs).

You can get the suffixes of a list using Data.List.tails.
This gives you a list of lists, you can then do the inner multiplications you want on this list with a function like:
prodAll [] = []
prodAll (h:t) = h:(map (* h) $ t)
You can then map this function over each inner list and concatenate the results:
f :: Num a => [a] -> [a]
f = concat . map prodAll . tails

Related

Rotations of a list in Haskell

I want to obtain a list of some of the rotations of the following string "I want to break free tonight". The constraint is that a rotation can not begin with the words "to" or "tonight". So the list of rotations is ["I want to break free today", "want to break free tonight I", "break free tonight I want to", "free tonight I want to break"].
I wrote the following functions:
rotate :: [l] -> [l]
rotate [] = []
rotate (x:xs) = (x:xs) ++ head(x:xs)
rotate1 :: [a] -> [[a]]
rotate1 xs = take (length xs) (iterate rotate xs)
main = do
print $ rotate1(words("I want to break free tonight"))
Running this code, I obtained all possible rotations, but they form a list of lists having elements like ["want", "I", "to", "break", "free", "tonight"] which is different from the string "want I to break free tonight". Also, I would want to see how I can drop the rotations that begin with the words "to", "tonight". I tried to use the filter function for the second part but I did not manage to solve the problem. Any help/hint is appreciated. I notice that I am a beginner in Haskell.
Running this code…
The code doesn't run. It has type errors.
First of all, let's fix the formatting so it's easier to read, and remove the extra parentheses
rotate :: [l] -> [l]
rotate [] = []
rotate (x:xs) = (x:xs) ++ head (x:xs)
rotate1 :: [a] -> [[a]]
rotate1 xs = take (length xs) (iterate rotate xs)
main = print $ rotate1 (words "I want to break free tonight")
This is weird:
rotate (x:xs) = (x:xs) ++ head (x:xs)
First of all, x:xs is the entire list, and x is the head of the list. For example, rotate [1, 2, 3] becomes:
rotate [1, 2, 3] = let x = 1
xs = [2, 3]
in (x:xs) ++ head (x:xs)
rotate [1, 2, 3] = (1:[2, 3]) ++ head (1:[2, 3])
rotate [1, 2, 3] = [1, 2, 3] ++ head [1, 2, 3]
rotate [1, 2, 3] = [1, 2, 3] ++ 1
-- type error
But ++ needs a list on both sides. What you probably want here is:
rotate (x:xs) = xs ++ [x]
Which gives us:
rotate [1, 2, 3] = let x = 1
xs = [2, 3]
in xs ++ [x]
rotate [1, 2, 3] = [2, 3] ++ [1]
rotate [1, 2, 3] = [2, 3, 1]
This is the same as:
rotate x = tail x ++ [head x]
For the rest of your problem… the filter should be straightforward since there is a filter function which does exactly what you need, and the unwords function turns lists of words back into strings.
You want the function intercalate :: [a] -> [[a]] -> [a] in Data.List.
From the hackage docs:
intercalate :: [a] -> [[a]] -> [a]
intercalate xs xss is equivalent to (concat (intersperse xs xss)). It
inserts the list xs in between the lists in xss and concatenates the
result.
In ghci
> import Data.List
> intercalate " " ["want", "I", "to", "break", "free", "tonight"]
> "want I to break free tonight"

Getting all the diagonals of a matrix in Haskell

The two-dimensional list looks like:
1 | 2 | 3
- - - - -
4 | 5 | 6
- - - - -
7 | 8 | 9
Or in pure haskell
[ [1,2,3], [4,5,6], [7,8,9] ]
The expected output for diagonals [ [1,2,3], [4,5,6], [7,8,9] ] is
[ [1], [4, 2], [7, 5, 3], [8, 6], [9] ]
Writing allDiagonals (to include anti-diagonals) is then trivial:
allDiagonals :: [[a]] -> [[a]]
allDiagonals xss = (diagonals xss) ++ (diagonals (rotate90 xss))
My research on this problem
Similar question here at StackOverflow
Python this question is about the same problem in Python, but Python and Haskell are very different, so the answers to that question are not relevant to me.
Only one This question and answer are in Haskell, but are only about the central diagonal.
Hoogle
Searching for [[a]] -> [[a]] gave me no interesting result.
Independent thinking
I think the the indexing follows a kind of count in base x where x is the number of dimensions in the matrix, look at:
1 | 2
- - -
3 | 4
The diagonals are [ [1], [3, 2], [4] ]
1 can be found at matrix[0][0]
3 can be found at matrix[1][0]
2 can be found at matrix[0][1]
1 can be found at matrix[1][1]
That is similar to counting in base 2 up to 3, that is the matrix size minus one. But this is far too vague to be translated into code.
Starting with universe-base-1.0.2.1, you may simply call the diagonals function:
Data.Universe.Helpers> diagonals [ [1,2,3], [4,5,6], [7,8,9] ]
[[1],[4,2],[7,5,3],[8,6],[9]]
The implementation in full looks like this:
diagonals :: [[a]] -> [[a]]
diagonals = tail . go [] where
-- it is critical for some applications that we start producing answers
-- before inspecting es_
go b es_ = [h | h:_ <- b] : case es_ of
[] -> transpose ts
e:es -> go (e:ts) es
where ts = [t | _:t <- b]
The key idea is that we keep two lists: a rectangular chunk we haven't started inspecting, and a pentagonal chunk (a rectangle with the top left triangle cut out!) that we have. For the pentagonal chunk, picking out the first element from each list gives us another diagonal. Then we can add a fresh row from the rectangular, un-inspected chunk to what's left after we delete that diagonal.
The implementation may look a bit unnatural, but it's intended to be quite efficient and lazy: the only thing we do to lists is destructure them into a head and tail, so this should be O(n) in the total number of elements in the matrix; and we produce elements as soon as we finish the destructuring, so it's quite lazy/friendly to garbage collection. It also works well with infinitely large matrices.
(I pushed this release just for you: the previous closest thing you could get was using diagonal, which would only give you [1,4,2,7,5,3,8,6,9] without the extra structure you want.)
Here is a recursive version, assuming that the input is always well-formed:
diagonals [] = []
diagonals ([]:xss) = xss
diagonals xss = zipWith (++) (map ((:[]) . head) xss ++ repeat [])
([]:(diagonals (map tail xss)))
It works recursively, going from column to column. The values from one column are combined with the diagonals from the matrix reduced by one column, shifted by one row to actually get the diagonals. Hope this explanation makes sense.
For illustration:
diagonals [[1,2,3],[4,5,6],[7,8,9]]
= zipWith (++) [[1],[4],[7],[],[],...] [[],[2],[5,3],[8,6],[9]]
= [[1],[4,2],[7,5,3],[8,6],[9]]
Another version that works on the rows instead of the columns, but based on the same idea:
diagonals [] = repeat []
diagonals (xs:xss) = takeWhile (not . null) $
zipWith (++) (map (:[]) xs ++ repeat [])
([]:diagonals xss)
Compared to the specified result, the resulting diagonals are reversed. This can of course be fixed by applying map reverse.
import Data.List
rotate90 = reverse . transpose
rotate180 = rotate90 . rotate90
diagonals = (++) <$> transpose . zipWith drop [0..]
<*> transpose . zipWith drop [1..] . rotate180
It first gets the main ([1,5,9]) and upper diagonals ([2,6] and [3]); then the lower diagonals: [8,4] and [7].
If you care about ordering (i.e. you think it should say [4,8] instead of [8,4]), insert a map reverse . on the last line.
One another solution:
diagonals = map concat
. transpose
. zipWith (\ns xs -> ns ++ map (:[]) xs)
(iterate ([]:) [])
Basically, we turn
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
into
[[1], [2], [3]]
[[] , [4], [5], [6]]
[[] , [] , [7], [8], [9]]
then transpose and concat lists. Diagonals are in the reversed order.
But that's not very efficient and doesn't work for infinite lists.
Here is one approach:
f :: [[a]] -> [[a]]
f vals =
let n = length vals
in [[(vals !! y) !! x | x <- [0..(n - 1)],
y <- [0..(n - 1)],
x + y == k]
| k <- [0 .. 2*(n-1)]]
For example, using it in GHCi:
Prelude> let f vals = [ [(vals !! y) !! x | x <- [0..(length vals) - 1], y <- [0..(length vals) - 1], x + y == k] | k <- [0 .. 2*((length vals) - 1)]]
Prelude> f [ [1,2,3], [4,5,6], [7,8,9] ]
[[1],[4,2],[7,5,3],[8,6],[9]]
Assuming a square n x n matrix, there will be n + n - 1 diagonals (this is what k iterates over) and for each diagonal, the invariant is that the row and column index sum to the diagonal value (starting with a zero index for the upper left). You can swap the item access order (swap !! y !! x with !! x !! y) to reverse the raster scanning order over the matrix.

Haskell: search list

I am new to Haskell, now I have a question here.
If I have a list [[1,2],[3,4],[5,6]], and I want use a function like searchList x = 3, then output 4, how to dual with it?
Use the filter high order function:
search :: [[Int]] -> Int -> Int
search list n = head (head (filter (\(x:xs) -> x == n) list))
What this search function does is to filter the elements of the passed list of lists, selecting only the ones which have the passed value n as head. Then takes only one (The first, thats why the first (right) head is used), and then extracts the first element of that list (Using head again).
If you want to store a list of pairs, I suggest you to use tuples instead of lists as elements of the list.
EDIT: As people suggested in comments, if you use tuples there is a function lookup on the prelude that implements this kind of searching.
So what you have a list of lists and you want to search it, find the element that matches [x,y] and return y.
searchList x (y:ys) = if x == head y then last y else searchList x ys
searchList x [] = -1
Which behaves like so:
Main> :load searchlist.hs
Main> searchList 3 [ [1, 2], [3, 4], [5, 6] ]
4
Main> searchList 5 [ [1, 2], [3, 4], [5, 6] ]
6
Main> searchList 6 [ [1, 2], [3, 4], [5, 6] ]
-1
As an aside it is uncommon to use lists in Haskell if you want a fixed width, like the pairs in your list. It would be more Haskell-ish to use a list of tuples, like so.
searchListTuples x (y:ys) = if x == fst y then snd y else searchListTuples x ys
searchListTuples x [] = -1
Which of course behaves very similarly:
Main> searchListTuples 3 [ (1,2), (3,4), (5,6) ]
4
Main> searchListTuples 5 [ (1,2), (3,4), (5,6) ]
6
Main> searchListTuples 6 [ (1,2), (3,4), (5,6) ]
-1
Try with :
searchList x y = last $ head $ dropWhile (\[a,_]->a/=x) y
Or, in pointfree notation:
searchList = ((last . head) .) . dropWhile . (. head) . (/=)
I like this recursive function, but a "-1" as a bad value is not a normal Haskell idiom. Use Maybe.
searchListTuples x (y:ys) = if x == fst y then Just (snd y) else SearchListTuples x ys
searchListTuples x [] = Nothing

Infinite loop in haskell

So I am writing a program to generate a list of prime numbers in haskell. I create two functions shown below:
{-
Given a list of prime numbers, this function will
add the next prime number to the list. So, given the
list [2, 3], it will return [2, 3, 5]
-}
nextPrime xs = xs ++ [lastVal + nextCounts]
where
lastVal = (head . reverse) $ xs
isNextPrime y = 0 `elem` ( map ( y `mod`) xs )
nextVals = (map isNextPrime [lastVal, lastVal+1 ..] )
nextCounts = length $ takeWhile (\x -> x) nextVals
allPrimes xs = allPrimes np
where
np = nextPrime xs
Now the function 'nextPrime' is doing what it is supposed to do. However, when I do a call to allPrimes as shown below:
take 5 $ allPrimes [2,3]
The program goes into an infinite loop. I thought Haskells "lazy" features were supposed to take care of all this? What am I missing??
If you start evaluating the expression on paper you can see why laziness doesn't help here. Start with your expression:
take 5 $ allPrimes [2,3]
First, attempt to evaluate the allPrimes expression:
allPrimes [2, 3]
which becomes
allPrimes np
where
np = nextPrime [2, 3]
put the things from the where clause into the expression and it becomes
allPrimes (nextPrime [2, 3])
Now, evaluate nextPrime [2, 3] (you can do this in ghci since that function works) and get [2, 3, 5], which you can replace in the previous expression, and it becomes
allPrimes [2, 3, 5]
repeat the above and it becomes
allPrimes [2, 3, 5, 7]
and there is your problem! allPrimes never evaluated to any values, it evaluates to allPrimes applied to longer and longer lists. To see where laziness does work, try evaluating on paper a function like zip from the Prelude:
zip :: [a] -> [b] -> [(a,b)]
zip (a:as) (b:bs) = (a,b) : zip as bs
zip [1, 2, 3] ['a', 'b', 'c']
a becomes 1, as becomes [2, 3], b becomes 'a', bs becomes ['b', 'c'] so you get
(1, 'a') : zip [2, 3] ['b', 'c']
The difference here is that there is a list with a value, then the rest of the list is an expression. In your allPrimes function, you just keep getting more expressions.
For more information, look into Weak Head Normal Form however if you are new to Haskell I recommend you get comfortable with the syntax and with the basics of "Thinking in Haskell" before you start looking at things like WHNF.
I'd read Drew's answer for a good explanation of what's going wrong, but for a quick demonstration for how to make this work,
nextPrime xs = xs ++ [lastVal + nextCounts]
where
lastVal = (head . reverse) $ xs
isNextPrime y = 0 `elem` ( map ( y `mod`) xs )
-- ^ Style note, this name is super misleading, since it returns
-- false when the number is prime :)
nextVals = (map isNextPrime [lastVal, lastVal+1 ..] )
nextCounts = length $ takeWhile (\x -> x) nextVals
allPrimes xs = last np : allPrimes np
where np = nextPrime xs
Now we're constructing the list as we go, and haskell is lazy so it can grab the last element of np before evaluating the allPrimes np. In other words head (a : infiniteLoop) is a, not an infinite loop.
However this is really innefficient. Lists are singly linked in Haskell so last is O(n) as opposed to O(1) in something like Python. And ++ is also costly, O(n) for the length of the first list.
Instead
nextPrime xs = lastVal + nextCounts
where lastVal = head xs
isNextPrime = 0 `elem` map (y `rem`) xs
nextVals = map isNextPrime [lastVal ..]
nextCount = length $ takeWhile id nextVals
allPrimes xs = p : allPrimes (p:xs)
where p = nextPrime xs
So we keep the list reversed to avoid those costly traversals. We can also simplify nextPrime
import Data.Maybe
nextPrime xs = fromJust nextPrime
where isPrime y = not $ 0 `elem` map (rem y) xs
nextPrime = find isPrime [head xs ..]
Where we just search the list for the first element which is prime and add it to our list. The fromJust is normally bad, if there were no next primes we'd get an error. But since we know mathematically that there will always be a next prime, this is safe.
In the end, the code looks like
import Data.Maybe
import Data.List
nextPrime xs = fromJust nextPrime
where isPrime y = 0 `notElem` map (rem y) xs
nextPrime = find isPrime [head xs ..]
allPrimes xs = p : allPrimes (p:xs)
where p = nextPrime xs
To evaluate it, call allPrimes [2].
An even cleaner way to do this would be to have a function isPrime that returns whether a number is prime or not. And then just to have
allPrimes = filter isPrime [1..]
But I'll leave that to the curious reader.
As Drew pointed out, your function allPrimes doesn't profit from lazyness since we never have acess to what it calculates. This is because the list we want to peek into is an argument of allPrimes, not a return value.
So we need to expose the list allPrimes is building, and still keep a function call that will infinitely build the following value of this list.
Well, since allPrimes is the re-application of itself over and over, we just need a function that exposes the intermediate values. And we have one!
iterate f a == [a, f (f a),...]
So with iterate and nextPrime, we could build the following (rather strange) functions:
-- nextPrime renamed as nextPrimeList
infiniteListofListofPrimes = iterate nextPrimeList [2,3]
primeN n = (infiniteListofListofPrimes !! n) !! n
takeN n = take n (infiniteListofListofPrimes !! n)
We are generating our primes, but it's not looking great. We would rather have [primes], not redundant [[some primes]].
The next step is building the list on WHNF:
elem1:elem2:aux
where aux = newvalue:aux
Where aux will calculate the newvalue and leave everything in place for the next one.
For that we need nextPrime sticking to generating one new prime:
nextPrime xs = lastVal + nextCounts
And finding the aux that can build listOfPrimes forever.
I came up with this:
infiniteListofPrimes = 2:3:aux 2
where aux n = nextPrime (take n infiniteListofPrimes):(aux (n+1))

Merge multiple lists if condition is true

I've been trying to wrap my head around this for a while now, but it seems like my lack of Haskell experience just won't get me through it. I couldn't find a similar question here on Stackoverflow (most of them are related to merging all sublists, without any condition)
So here it goes. Let's say I have a list of lists like this:
[[1, 2, 3], [3, 5, 6], [20, 21, 22]]
Is there an efficient way to merge lists if some sort of condition is true? Let's say I need to merge lists that share at least one element. In case of example, result would be:
[[1, 2, 3, 3, 5, 6], [20, 21, 22]]
Another example (when all lists can be merged):
[[1, 2], [2, 3], [3, 4]]
And it's result:
[[1, 2, 2, 3, 3, 4]]
Thanks for your help!
I don't know what to say about efficiency, but we can break down what's going on and get several different functionalities at least. Particular functionalities might be optimizable, but it's important to clarify exactly what's needed.
Let me rephrase the question: For some set X, some binary relation R, and some binary operation +, produce a set Q = {x+y | x in X, y in X, xRy}. So for your example, we might have X being some set of lists, R being "xRy if and only if there's at least one element in both x and y", and + being ++.
A naive implementation might just copy the set-builder notation itself
shareElement :: Eq a => [a] -> [a] -> Bool
shareElement xs ys = or [x == y | x <- xs, y <- ys]
v1 :: (a -> a -> Bool) -> (a -> a -> b) -> [a] -> [b]
v1 (?) (<>) xs = [x <> y | x <- xs, y <- xs, x ? y]
then p = v1 shareElement (++) :: Eq a => [[a]] -> [[a]] might achieve what you want. Except it probably doesn't.
Prelude> p [[1], [1]]
[[1,1],[1,1],[1,1],[1,1]]
The most obvious problem is that we get four copies: two from merging the lists with themselves, two from merging the lists with each other "in both directions". The problem occurs because List isn't the same as Set so we can't kill uniques. Of course, that's an easy fix, we'll just use Set everywhere
import Data.Set as Set
v2 :: (a -> a -> Bool) -> (a -> a -> b) -> Set.Set a -> Set.Set b
v2 (?) (<>) = Set.fromList . v1 (?) (<>) . Set.toList
So we can try again, p = v2 (shareElementonSet.toList) Set.union with
Prelude Set> p $ Set.fromList $ map Set.fromList [[1,2], [2,1]]
fromList [fromList [1,2]]
which seems to work. Note that we have to "go through" List because Set can't be made an instance of Monad or Applicative due to its Ord constraint.
I'd also note that there's a lot of lost behavior in Set. For instance, we fight either throwing away order information in the list or having to handle both x <> y and y <> x when our relation is symmetric.
Some more convenient versions can be written like
v3 :: Monoid a => (a -> a -> Bool) -> [a] -> [a]
v3 r = v2 r mappend
and more efficient ones can be built if we assume that the relationship is, say, an equality relation since then instead of having an O(n^2) operation we can do it in O(nd) where d is the number of partitions (cosets) of the relation.
Generally, it's a really interesting problem.
I just happened to write something similar here: Finding blocks in arrays
You can just modify it so (although I'm not too sure about the efficiency):
import Data.List (delete, intersect)
example1 = [[1, 2, 3], [3, 5, 6], [20, 21, 22]]
example2 = [[1, 2], [2, 3], [3, 4]]
objects zs = map concat . solve zs $ [] where
areConnected x y = not . null . intersect x $ y
solve [] result = result
solve (x:xs) result =
let result' = solve' xs [x]
in solve (foldr delete xs result') (result':result) where
solve' xs result =
let ys = filter (\y -> any (areConnected y) result) xs
in if null ys
then result
else solve' (foldr delete xs ys) (ys ++ result)
OUTPUT:
*Main> objects example1
[[20,21,22],[3,5,6,1,2,3]]
*Main> objects example2
[[3,4,2,3,1,2]]

Resources