Reputation: 1
secondTest :: [(Int, Int)] -> [Int] -> [Int]
secondTest a b = [ x | (m,n) <- a, x <- b, m > 3 && n > 3]
I have this code at the moment and I want to change it so that it will return b if all of the int given are more than 3, no matter how many ints are given in the first list.
I have tried something like this:
secondTest :: [Int] -> [Int] -> [Int]
secondTest a b = [ x | m <- a, x <- b, m > 3]
but this returns a value if any of the int values are more than 3, rather than all of them.
edit to show expected return:
secondTest [4,4] [1,2] = [1,2]
secondTest [4,4,4] [1,2] = [1,2]
secondTest [4,1,4] [1,2,9] = Nothing
Thanks
Upvotes: 0
Views: 198
Reputation: 116174
You can test if all the elements of a
are larger than 3 using all
:
secondTest :: [Int] -> [Int] -> [Int]
secondTest a b
| all (> 3) a = b
| otherwise = ...
Note that in the otherwise
case we still have to return a list, so we can't return Nothing
. We can return an empty list
secondTest a b
| all (> 3) a = b
| otherwise = []
or we can change the return type of the function
secondTest :: [Int] -> [Int] -> Maybe [Int]
secondTest a b
| all (> 3) a = Just b
| otherwise = Nothing
You can't directly do this with a list comprehension. At best, you could use one to generate the list of elements that are <= 3
, and then test whether that is empty, reversing the logic:
secondTest a b
| null [ x | x <- a, x <= 3 ] = Nothing
| otherwise = Just b
Upvotes: 2