简体   繁体   English

如果 x 在列表中,则返回 true,否则返回 False(递归)

[英]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.我正在编写一个简短的递归 function 以将列表作为输入,output 是一个布尔值。 (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. (我是 haskell 初学者)到目前为止,我可以检测第一个元素是否为 3,但我不确定如何使用递归来检查列表的 rest。

func :: [Int] -> Bool
func [] = False
func (x:xs)
  | (x == 3)           = True
  | otherwise          = False

I'm new to Haskell too.我也是 Haskell 的新手。

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如果列表为空:没有 3
  • if list is no empty:如果列表不为空:
    1. if head is 3, then we have 3如果 head 是 3,那么我们有 3
    2. otherwise we should check rest of the list, so answer of "3 is in list" is equivalent to " x is in xs".否则我们应该检查列表的 rest,所以“3 在列表中”的答案等同于“x 在 xs 中”。

if you accept a little change, i can suggest implementing with OR (and help of lazy evaluation).如果您接受一点更改,我可以建议使用 OR 实施(以及惰性评估的帮助)。

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.如果 head 为 3,则返回 True。
  • if head is not 3, check rest of list.如果 head 不是 3,请检查列表的 rest。

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.最后给大家介绍一下elem function,它的作用是:获取一个元素和一个列表,如果a在列表中则返回True,否则返回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.祝您学习 Haskell 好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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