简体   繁体   中英

How can I pass a list of unknown length to a haskell function?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM