I have a data object for trees like this:
data Tree = Empty | Node Int [Tree] deriving (Show, Eq)
Here is my searching function:
searchValueTree :: Tree -> Int -> Bool
searchValueTree Empty _ = False
searchValueTree (Node a list) valueSearch
| a == valueSearch = True
| otherwise = helperTree list valueSearch
--help function
helperTree :: [Tree] -> Int -> Bool
helperTree [] _ = False
helperTree (x:xs) value = searchValueTree x value || helperTree xs value
test::Bool
test = searchValueTree (Node 5 [Node 4 [Node 3 [Empty]], Node 7 [Empty], Leer]) 3
The question is, when I'm in the helper function and I call searchValueTree x value
and I haven't found my value, which is called first: helperTree list valueSearch
in searchValueTree
, or helperTree xs value
in helperTree
?
I can't figure out the order of execution.
CodePudding user response:
It goes something like this:
searchValueTree x value || helperTree xs value
-> {- definition of || -}
case searchValueTree x value of
True -> True
False -> helperTree xs value
-> {- pattern match forces evaluation of the call to searchValueTree -}
case (case x of
Empty -> False
Node a list | a == value -> True
| otherwise -> helperTree list value
) of
True -> True
False -> helperTree xs value
-> {- assuming x matches Node a list and a /= value -}
case let Node _ list = x in helperTree list value of
True -> True
False -> helperTree xs value
I believe in your parlance this means that helperTree list valueSearch
is called in searchValueTree
before helperTree xs value
is called in helperTree
. From here, because the first argument to (||)
has not yet reached a form that lets the pattern match choose between its branches, evaluation continues in the scrutinee of the case, namely in let Node _ list = x in helperTree list value
.