简体   繁体   中英

Haskell Problem in all / map functions

func::[Int]->Bool
func [] = False
func (l:ls) = ff1 (l)


ff1::Int->Bool
ff1 j = j > 0

Currently this code only matches the first value. I tryied using map and all but didn't get a good result.

My problem is that I need to check if all the values are matching the ff1 's pattern and if all the ls list elements are true or false , returning a single boolean.

I think you just need all :

Prelude> :t all
all :: (a -> Bool) -> [a] -> Bool
Prelude> all (>0) [-10..10]
False
Prelude> all (>0) [1..10]
True

Or, if you want, you can do:

Prelude> let f1 x = x > 5 && x < 10
Prelude> let func xs = all f1 xs
Prelude> func [6..9]
True
Prelude> func [1..10]
False

which allows you to create a function f1 to do a complex check. In any case, you can use all for your func

This should work:

func ls = all ff1 ls

Or this:

func ls = and (map ff1 ls)

Maybe something like this -- assuming you wish to perform an "and" between all Bool results.

func::[Int]->Bool
func [] = True
func (l:ls) = ff1 (l) && func (ls)

ff1::Int->Bool
ff1 j = j > 0

main = do let a = func [-1, -2, 1, 2, 3]
          print a

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