I'm writing a short recursive function to take a list as input and output a Bool. (I'm haskell beginner) So far I can detect if the first element is a 3 or not, but I'm not sure how to use recursion to check the rest of the list.
func :: [Int] -> Bool
func [] = False
func (x:xs)
| (x == 3) = True
| otherwise = False
I'm new to Haskell too.
by a little change to your code, it could be re-written as
func :: [Int] -> Bool
func [] = False
func (x:xs)
| x == 3 = True
| otherwise = func xs
explain:
if you accept a little change, i can suggest implementing with OR (and help of lazy evaluation).
func :: [Int] -> Bool
func [] = False
func (x:xs) = x==3 || func xs
it is really same as the upper code, but with less lines.
at last, I want to introduce you elem
function, it works as: get an element and a list, return True if a is in list, otherwise False. It is exactly what we want here, so i write:
containsThree :: [Int] -> Bool
containsThree = elem 3
also note that I used point-free style, if you are not familiar, second line is same as:
containsThree xs = elem 3 xs
Good luck learning Haskell.
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.