简体   繁体   中英

Return true if x is in list else False (Recursion)

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 list is empty: there is no 3
  • if list is no empty:
    1. if head is 3, then we have 3
    2. otherwise we should check rest of the list, so answer of "3 is in list" is equivalent to " x is in xs".

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.

  • if head is 3, return True.
  • if head is not 3, check rest of list.

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.

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