I have some problem with list comprehension, if the input is a list.
In these all III excercises it's not allowed to use: map
, filter
and concat
!!!
Part I
Requirements:
A funktion f1
gets a list xs
of tripels (a, b, cs)
where
a
and b
are of type Int
c
is of type [Int]
The function should generate a list of pairs (a · b, b + c)
, for all c in cs AND in the generated list should appear just those pairs in which the 1st element is bigger than the 2nd one - (a · b) > b + c
.
Example:
f1 [(10,20,[1,10,100]), (4,5,[5,15,25])]
should return the following list:
[(200,21),(200,30),(200,120),(20,10)]
My attempts:
f1 :: Int -> Int -> [Int] -> [(Int, Int)]
f1 a b cs = [(a*b, b+c)| c<-cs, (a*b)>(b+c)]
It works fine, however not for lists as input.
So I tried several ways, but unfortunately not the right one :-(
f1 :: [(Int, Int, [Int])] -> [(Int, Int)]
1st approach:
f1 xs = [((xs !! 0)*(xs !! 1), (xs !! 1)+c)| c<-(xs !! 2), ((xs !! 0)*(xs !! 1))>((xs !! 1)+c)]
2nd approach:
f1 let (a, b, cs) = xs = [(a*b, b+c)| c<-cs, (a*b)>(b+c)]
3rd approach:
f1 (a b cs) = [(a*b, b+c)| c<-cs, (a*b)>(b+c)]
All three don't work!
Solution by dave4420:
f1 :: [(Int, Int, [Int])] -> [(Int, Int)]
f1 xs = [ (a*b, b+c) | (a, b, cs) <- xs, c <- cs, (a*b)>(b+c) ]
Part II
Requirements:
A function g1 gets a list of pairs of same type and generate a plain list out of it.
Example:
g1 [(1,2),(3,4),(5,6)] returns [1,2,3,4,5,6]
My Attempt:
g1 :: [(Int, Int)] -> [Int]
g1 xs = [a,b | (a,b)<-xs]
I get a compiling error for this because a,b in the output of list comprehension does not have the correct syntax.
However I can return a or b or e.g. a+b:
g1 xs = [a | (a,b)<-xs]
or
g1 xs = [a+b | (a,b)<-xs]
Could you please help me out of this too?
Thanks once again
Part III is coming...