[英]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 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.它实际上与上面的代码相同,但行数更少。
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.