I have the following problem, I want to write a function that generates nested lists and then unpacks the nested lists into a single list.
A function that generates nested lists of a dynamic degree depending on its arguments obviously does not type-check, as the return type would vary depending on the arguments. However is it possible to recursively unpack lists to always return a flat list?
Suppose the non-possible function would return this for an argument of 2:
[ [ [a], [b] ], [ [c], [d] ] ]
and this for an argument of 3:
[[[[a], [b], [c]], [[d], [e], [f]], [[g], [h], [i]]], [[[j], [k], [l]], [[m], [n], [o]], [[p], [q], [r]]], [[[s], [t], [u]], [[v], [w], [x]], [[y], [z], [a1]]]]
Now I would like to have some function that I can put into the recursive call that would result in something like this:
[ unpack [ unpack [a], unpack [b] ], unpack [ unpack [c], unpack [d] ] ]
which in turn would evaluate to [a, b, c, d]
I was able to write something like this for list of only one element:
unpack [x] = x
f 1 = [0]
f n = [unpack $ f x | x <- [1..n-1]]
*Main> f 3
[0,0]
But obviously it fails for 4:
*Main> f 4
[0,0,*** Exception: Non-exhaustive patterns in function unpack
Manual "trace":
f 3 = [unpack $ f x | x <- [1..3-1]]
= [ unpack $ f 1, unpack $ f 2]
= [ unpack [0], unpack [f x | x <- [1..2-1]]]
= [ unpack [0], unpack [f 1] ]
= [ unpack [0], unpack [0] ]
= [0, 0]
Is such a function theoretically possible? I have a strong feeling that not... but maybe that feeling is wrong.
If it has not become clear yet what I have in mind: This [unpack [1,2,3]] would result in the list [1,2,3].
As written in the comments, the program you want is not possible in Haskell.
Here's a possible alternative: Create a datatype
data Unpack a = Unpack [Unpack a] | Elem a
deriving (Eq, Ord)
Further you can write a function which evaluates the unpacking:
unpacked :: [Unpack a] -> [a]
unpacked [] = []
unpacked (Unpack x : xr) = unpacked x ++ unpacked xr
unpacked (Elem x : xr) = x : unpacked xr
Let's make the output prettier:
instance Show a => Show (Unpack a) where
show (Unpack xs) = show xs
show (Elem x) = show x
Example usage in ghci:
> list = [Unpack [Elem 1, Unpack [Elem 3, Elem 4]], Unpack [Elem 5, Elem 6, Elem 7]]
[[1,[3,4]],[5,6,7]]
> unpacked list
[1,3,4,5,6,7]
Related
My Problem is that I want to create a infinite list of all combinations of a given list. So for example:
infiniteListComb [1,2] = [[],[1],[2], [1,1],[1,2],[2,1],[2,2], [1,1,1], ...].
other example:
infiniteListComb [1,2,3] = [[], [1], [2], [3], [1,1], [1,2], [1,3], [2,1],[2,2],[2,3],[3,1],[3,2],[3,3],[1,1,1], ...].
Reminds me of power sets, but with lists with same elements in it.
What I tried:
I am new in Haskell. I tried the following:
infiniteListComb: [x] -> [[x]]
infiniteListComb [] = []
infiniteListComb [(x:xs), ys] = x : infiniteListComb [xs,ys]
But that did not work because it only sumed up my list again. Has anyone another idea?
Others already provided a few basic solutions. I'll add one exploiting the Omega monad.
The Omega monad automatically handles all the interleaving among infinitely many choices. That is, it makes it so that infiniteListComb "ab" does not return ["", "a", "aa", "aaa", ...] without ever using b. Roughly, each choice is scheduled in a fair way.
import Control.Applicative
import Control.Monad.Omega
infiniteListComb :: [a] -> [[a]]
infiniteListComb xs = runOmega go
where
go = -- a combination is
pure [] -- either empty
<|> -- or
(:) <$> -- a non empty list whose head is
each xs -- an element of xs
<*> -- and whose tail is
go -- a combination
Test:
> take 10 $ infiniteListComb [1,2]
[[],[1],[1,1],[2],[1,1,1],[2,1],[1,2],[2,1,1],[1,1,1,1],[2,2]]
The main downside of Omega is that we have no real control about the order in which we get the answers. We only know that all the possible combinations are there.
We iteratively add the input list xs to a list, starting with the empty list, to get the ever growing lists of repeated xs lists, and we put each such list of 0, 1, 2, ... xs lists through sequence, concatting the resulting lists:
infiniteListComb :: [a] -> [[a]]
infiniteListComb xs = sequence =<< iterate (xs :) []
-- = concatMap sequence (iterate (xs :) [])
e.g.
> take 4 (iterate ([1,2,3] :) [])
[[],[[1,2,3]],[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3],[1,2,3]]]
> sequence [[1,2,3],[1,2,3]]
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
> take 14 $ sequence =<< iterate ([1,2,3] :) []
[[],[1],[2],[3],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3],[1,1,1]]
The essence of Monad is flatMap (splicing map).
sequence is the real magician here. It is equivalent to
sequence [xs, ys, ..., zs] =
[ [x,y,...,z] | x <- xs, y <- ys, ..., z <- zs ]
or in our case
sequence [xs, xs, ..., xs] =
[ [x,y,...,z] | x <- xs, y <- xs, ..., z <- xs ]
Coincidentally, sequence . replicate n is also known as replicateM n. But we spare the repeated counting from 0 to the growing n, growing them by 1 at a time instead.
We can inline and fuse together all the definitions used here, including
concat [a,b,c...] = a ++ concat [b,c...]
to arrive at a recursive solution.
Another approach, drawing on answer by chi,
combs xs = ys where
ys = [[]] ++ weave [ map (x:) ys | x <- xs ]
weave ((x:xs):r) = x : weave (r ++ [xs])
There are many ways to implement weave.
Since list Applicative/Monad works via a cartesian-product like system, there's a short solution with replicateM:
import Control.Monad
infiniteListComb :: [x] -> [[x]]
infiniteListComb l = [0..] >>= \n -> replicateM n l
I'm having trouble with an assignment from my Haskell class. I have already solved a partial problem of this task: I have to write a function that takes an Int and creates an infinite list with the multiples of that Int.
function :: Int -> [Int]
function d = [d*x | x <- [1..]]
Console:
ghci> take 10 (function 3)
gives
[3,6,9,12,15,18,21,24,27,30]
In the second task I have to extend the function so that it accepts a list of numbers and uses each value of that list as a factor (d previously). For example:
ghci> take 10 (function [3, 5])
should give
[3,5,6,9,10,12,15,18,20,21]
Already tried a list comprehension like
function d = [y*x | y <- [1..], x <- d]
but the function returns the list in an unsorted form:
[3,5,6,10,9,15,12,20,15,25]
We got the tip that we should use the modulo function of Haskell, but I have no real idea how to proceed exactly. Do you have a good tip for me?
If you think of d being a factor not as
y = x * d
but instead
y `mod` d == 0,
then you can source the list comprehension from the list [1..] and add a predicate function, for example:
function ds
| null ds = [1..]
| otherwise = [ x | x <- [1..], qualifies x ]
where
qualifies x = any (==0) $ (flip mod) <$> ds <*> [x]
A more expressive version which is perhaps easier to grasp in the beginning:
function' ds
| null ds = [1..]
| otherwise = [ x | x <- [1..], divByAnyIn ds x ]
where
divByAnyIn ds x =
case ds of
(d:ds') -> if x `mod` d == 0 then True
else divByAnyIn ds' x
_ -> False
I have a one liner.
import Data.List (nub)
f xs = nub [x|x<-[1..], d<-xs, x `mod` d == 0]
take 10 $ f [3,5] -- [3,5,6,9,10,12,15,18,20,21]
runtime should be O(n² + n*d) from the resulting list. The nub runs in O(n²). Would be nice to get rid of it.
g xs = [x |x<-[1..], let ys = map (mod x) xs in 0 `elem` ys]
This performs pretty ok. It should run in O (n*d). I also have this version which I thought performs at least as well as g, but apparently it performs better than f and worse than g.
h xs = [x |x<-[1..], or [x `mod` d == 0 |d<-xs] ]
I am not sure why that is, or is lazy as far as I can tell and I don`t see any reason why it should run slower. It especially does not scale as well when you increase the length of the input list.
i xs = foldr1 combine [[x, x+x ..] |x<- sort xs]
where
combine l [] = l
combine [] r = r
combine l#(x:xs) r#(y:ys)
| x < y = (x: combine xs r)
| x > y = (y: combine l ys)
| otherwise = (x: combine xs ys)
Not a one liner anymore, but the fastest I could come up with. I am not a hundred percent sure why it makes such a big difference on runtime if you right or left fold and if you sort the input list in advance. But it should not make a difference on the result since:
commutative a b = combine [a] [b] == combine [b] [a]
I find it completely insane to think about this Problem in terms of folding a recursive function over a list of endless lists of multiples of input coefficients.
On my System it is still about a factor of 10 slower than another solution presented here using Data.List.Ordered.
The answer here just shows the idea, it is not a optimized solution, there may exists many way to implement it.
Firstly, calculate all the value of each factors from the inputted list:
map (\d->[d*x|x<-[1..]]) xs
For example: xs = [3, 5] gives
[[3, 6, 9, ...], [5, 10, 15, ...]]
then, find the minimum value of 1st element of each list as:
findMinValueIndex::[(Int, [Int])]->Int
findMinValueIndex xss = minimum $
map fst $
filter (\p-> (head $ snd p) == minValue) xss
where minValue = minimum $ map (head . snd) xss
Once we found the list hold the minimum value, return it and remove the minimum value from list as:
sortMulti xss =
let idx = findMinValueIndex $ zip [0..] xss
in head (xss!!idx):sortMulti (updateList idx (tail $ xss!!idx) xss
So, for example, after find the first value (i.e. 3) of the result, the lists for find next value is:
[[6, 9, ...], [5, 10, 15, ...]]
repeat above steps we can construct the desired list. Finally, remove the duplicated values. Here is the completed coding:
import Data.Sequence (update, fromList)
import Data.Foldable (toList)
function :: [Int] -> [Int]
function xs = removeDup $ sortMulti $ map (\d->[d*x|x<-[1..]]) xs
where sortMulti xss =
let idx = findMinValueIndex $ zip [0..] xss
in head (xss!!idx):sortMulti (updateList idx (tail $ xss!!idx) xss)
removeDup::[Int]->[Int]
removeDup [] = []
removeDup [a] = [a]
removeDup (x:xs) | x == head xs = removeDup xs
| otherwise = x:removeDup xs
findMinValueIndex::[(Int, [Int])]->Int
findMinValueIndex xss = minimum $
map fst $
filter (\p-> (head $ snd p) == minValue) xss
where minValue = minimum $ map (head . snd) xss
updateList::Int->[Int]->[[Int]]->[[Int]]
updateList n xs xss = toList $ update n xs $ fromList xss
There is a pretty nice recursive solution
function' :: Int -> [Int]
function' d = [d * x | x <- [1..]]
braid :: [Int] -> [Int] -> [Int]
braid [] bs = bs
braid as [] = as
braid aa#(a:as) bb#(b:bs)
| a < b = a:braid as bb
| a == b = a:braid as bs # avoid duplicates
| otherwise = b:braid aa bs
function :: [Int] -> [Int]
function ds = foldr braid [] (map function' ds)
braid function builds the desired list "on the fly" using only input's head and laziness
If you want to do it with the modulo function, you can define a simple one-liner
foo ds = filter (\x -> any (== 0) [mod x d | d <- ds]) [1..]
or, in the more readable form,
foo ds = filter p [1..]
where
p x = any id [ mod x d == 0 | d <- ds]
= any (== 0) [ mod x d | d <- ds]
= not $ null [ () | d <- ds, mod x d == 0]
= null [ () | d <- ds, mod x d /= 0]
= null [ () | d <- ds, rem x d > 0]
With this, we get
> take 20 $ foo [3,5]
[3,5,6,9,10,12,15,18,20,21,24,25,27,30,33,35,36,39,40,42]
But, it is inefficient: last $ take 20 $ foo [300,500] == 4200, so to produce those 20 numbers this code tests 4200. And it gets worse the bigger the numbers are.
We should produce n numbers in time roughly proportional to n, instead.
For this, first write each number's multiples in their own list:
[ [d*x | x <- [1..]] | d <- ds ] ==
[ [d, d+d ..] | d <- ds ]
Then, merge these ordered increasing lists of numbers in an ordered fashion to produce one ordered non-decreasing list of numbers. The package data-ordlist has many functions to deal with this kind of lists:
import qualified Data.List.Ordered as O
import Data.List (sort)
bar :: (Ord a, Num a, Enum a) => [a] -> [a]
bar ds = foldr O.merge [] [ [d, d+d ..] | d <- ds ]
= O.foldt' O.merge [] [ [d, d+d ..] | d <- ds ] -- more efficient,
= O.mergeAll [ [d, d+d ..] | d <- sort ds ] -- tree-shaped folding
If we want the produced list to not contain any duplicates, i.e. create an increasing list, we can change it to
baz ds = O.nub $ foldr O.merge [] [ [d, d+d ..] | d <- ds ]
= foldr O.union [] [ [d, d+d ..] | d <- ds ]
= O.foldt' O.union [] [ [d, d+d ..] | d <- ds ]
= O.unionAll [ [d, d+d ..] | d <- sort ds ]
= (O.unionAll . map (iterate =<< (+)) . sort) ds
Oh, and, unlike the quadratic Data.List.nub, Data.List.Ordered.nub is linear, spends O(1) time on each element of the input list.
I am trying to use recursion and higher-order functions to do something to the first element of a list and then to every other element in the list, so for example add 3 to the 1st, 3rd, 5th.. etc.
The problem I am having is that it gives me the non-exhaustive pattern error. Any help would be appreciated. Here is what I have so far:
applyToEveryOther :: (a -> b) -> [a] -> [b]
applyToEveryOther _ [] = []
applyToEveryOther f (x:y:xs) = f x : applyToEveryOther f xs
and these are some additional lines that I have tried but don't help:
applyToEveryOther _ [x] = f x
applyToEveryOther f [x] = f x
The single element case should also return a List (of type [b]):
applyToEveryOther f [x] = [f x]
Another solution that doesn't use explicit recursion, but just higher-order functions:
import Data.List (cycle)
applyToEveryOther f = zipWith ($) (cycle [f, id])
cycle creates an infinite list of alternating functions f, id, f, id, etc.
zipWith ($) applies the functions in the list to the corresponding elements of your input list.
[(+1), id, (+1), id, (+1), id, (+1), id, ...]
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
=============================================
[ 2, 2, 4, 4, 6, 6, 8, 8 ]
(Hat tip: the problem of applying a list of functions piecewise to a list of arguments, along with a solution using zipWith ($), appeared recently on the 1HaskellADay twitter feed.)
(My own inferior solution was to use the ZipList type constructor found in Control.Applicative; applied here, it would look something like
import Control.Applicative
applyToEveryOther f xs = let fs = cycle [f,id]
in getZipList (ZipList fs <*> ZipList xs)
)
Lets say I have nested lsit: [1, [2, 3, 4], [5, [6]]] and I want to count how many elements it has. In this case it is six elements. I have written such code for doing this:
totalElems :: [a] -> Int
totalElems (x:xs) = case (x, xs) of
(_, []) -> 0
(y:ys, _) -> 1 + totalElems ys + totalElems xs
(_, _) -> 1 + totalElems xs
But I've got an error:
a.hs:4:42:
Couldn't match expected type ‘a’ with actual type ‘[a0]’
‘a’ is a rigid type variable bound by
the type signature for totalElems :: [a] -> Int at a.hs:1:15
Relevant bindings include
xs :: [a] (bound at a.hs:2:15)
x :: a (bound at a.hs:2:13)
totalElems :: [a] -> Int (bound at a.hs:2:1)
In the pattern: y : ys
In the pattern: (y : ys, _)
In a case alternative:
(y : ys, _) -> 1 + totalElems ys + totalElems xs
How I can do this in Haskell?
You can't make freeform lists-within-lists like that in Haskell. Dynamically typed langues will tolerate silliness like that, but strongly-typed Haskell won't.
1 is of type Int, and [2,3,4] is of a different type [Int]. Things in a list have to be of the same type.
However, you could do something like this:
data Nest a = Elem a | List [Nest a]
example ::Nest Int
example = List [Elem 1, List [Elem 2, Elem 3, Elem 4], List [Elem 5, List [Elem 6]]]
countNest :: Nest a -> Int
countNest (Elem x) = 1
countNest (List xs) = sum $ map countNest xs
Let's say I have nested lsit: [1, [2, 3, 4], [5, [6]]]
You can't have that list. It won't type-check. Try typing it by itself in GHCi; it'll just spit an error message at you. Since this input can't exist in the first place, trying to write a function to process it is a doomed endeavor.
Instead, you need to define a custom data type for this. See the other answers.
As others have said, the simplest way to do this is with a different data structure, like the tree NovaDenizen defined. However, just so you know, Haskell's type system enables various ways of creating "lists" in which the elements have different types : see https://wiki.haskell.org/Heterogenous_collections
I am making a function that takes a boolean function and two lists. It needs to iterate through the first list and for the indices that make the boolean function true return the corresponding elements of the second list.
for example..
filterAB (>0) [-2, -1, 0, 1, 2] [5, 2, 5, 9, 0]
would return:
[9, 0]
I am using findIndices to return a list of the correct indices from the first list that make the boolean function true so that i can use them to access the elements of the second list. Here is my code so far:
filterAB boolFunc listA listB = take listC listB where
listC = findIndices boolFunc listA
Unfortunately the line
take listC listB
does not work because the take function requires type Int as a specifier while listC is type [Int]
Any help would be greatly appreciated!
Also using simple list comprehensions ...
[ghci] let filterAB f as bs = [ b | (a, b) <- zip as bs, f a]
[ghci] filterAB (>0) [-2,-1,0,1,2] [5,2,5,9,0]
[9,0]
[ghci]
An other version :
filterAB f l1 l2 = map snd $ filter (f . fst) $ zip l1 l2
If you have difficulties understanding the $, this version is the same :
let filterAB f l1 l2 = map snd ( filter (f . fst) ( zip l1 l2 ))
zip take two list and transform it one a list of tuple. For example :
zip [1,2,3,4] ["un", "deux", "trois", "quatre"] == [(1,"un"),(2,"deux"),(3,"trois"),(4,"quatre")]
filter take a list and a function that return true of false for each element of the list and filter it, it's like your filterAB but in simpler :
filter (>0) [-1, 2, -2, 3, -3] == [2,3]
fst take a couple and return the first element, so f . fst will apply f on the first element of your tuple. Like that filter (f . fst) allow use to filter on a list of tuple by just considering the first element of each tuple :
filter (odd . fst) [(1,"un"),(2,"deux"),(3,"trois"),(4,"quatre")] == [(1,"un"),(3,"trois")]
If you don't get the dot, it's just function composition so the next two lines are identical :
h = f . g
h = f ( g x )
snd take a couple and return the second element. Using it with map allow us to take a list of tuple and return a list only of the second element of the tuple :
map snd [(1,"un"),(2,"deux"),(3,"trois"),(4,"quatre")] == ["un","deux","trois","quatre"]
Try this
filterAB f (x:xs) (y:ys)
| f x = y : filterAB f xs ys
| otherwise = filterAB f xs ys
filterAB _ _ _ = []
Chapter 3. Defining Types, Streamlining Functions of Real World Haskell given a very good explanation of the syntax involved here.
Testing:
*Main> filterAB (>0) [-2,-1,0,1,2] [5,2,5,9,0]
[9,0]
*Main> filterAB (>0) [-2,-1,0,1,2] [5,2,5,9]
[9]
*Main> filterAB (>0) [-2,-1,0,1,2] [5,2,5]
[]
*Main> filterAB (>0) [-2,-1,0] [5,2,5,9,0]
[]
*Main>