I'm trying to write a fcn that takes in a list of tuple and an expression (I am working on a postfix expression eval). This function should loop through the expression and find the same letter in the tuple. If it's a match then it returns the int value corresponding to that letter in the tuple. When I ran the code below, my program compiled and run but then it was hanging during execution. What did I do wrong?
let rec getVar ls exp =
match ls with
|head::tl when (fst head) = exp -> printfn "%d" (snd head)
| _ -> getVar ls exp
let ls = [("a",5);("b",2);("c",3)]
let exp = "ab+"
getVar ls exp
Your
match
expression has a final catch-all clause (the_
clause) that just callsgetVar
again with the same parameters. If thewhen (fst head) = exp
condition fails, then code falls through to the catch-all clause, sogetVar
gets called again with the same parameters, so the first condition will fail, so code falls through to the catch-all clause, sogetVar
gets called again... It's an infinite loop.What you probably meant to do was call
getVar
again on the tail of the list if yourwhen
condition failed:You also need to think about what you'll do if the list is empty (i.e., you need a match condition that matches against
[]
). I'll leave that one up to you, since there are many things you could want to do with an empty list and it's not obvious which one you'd want.