Why does the following piece of code need to have two vertical bars ||
?
data Tree = Leaf Int
| Node Tree Int Tree
occurs :: Int -> Tree -> Bool
occurs m (Leaf n) = m==n
occurs m (Node l n r) = m==n
|| occurs m l
|| occurs m r
CodePudding user response:
||
is the logical or operator. It bails out early if it evaluates to True
and doesn't further search the tree.
Another way to implement it is to use the function or that may make it more readable:
occurs :: Int -> Tree -> Bool
occurs m (Leaf n) = m==n
occurs m (Node l n r) = or [m==n, occurs m l, occurs m r]
A small test:
λ> t = Node (Node (Leaf 1) 3 (Leaf 2)) 4 (Leaf 5)
λ> occurs 10 t
False
λ> occurs 3 t
True