I'm working on Learn You a Haskell. On the "fold" section, I need to implement elem
(given an element, find out if it's in the list - True or False).
def myElem(a: Char, as: List[Char]): Boolean = as match {
case Nil => false
case x::Nil => println(x); if(x == a) true else false
case x::_ => println(x); as.foldLeft(false){ (_, elem) =>
if(a == elem) true
else myElem(a, as.tail)
}
}
However, it's failing on a simple example:
scala> myElem('a', "ab".toList)
a
b
res8: Boolean = false
What am I doing wrong here? Also, as extra, I'd appreciate any suggestion on improvement of this code.
As an aside, I would think a find
would be more appropriate here.