4

I thought I'd be getting along alright with F# since I'm decent at Haskell, but I feel like I'm being stumped by dead simple issues. I have some parsing code for a simple JSON parser, like this:

let rec parseObject tokens = function
 | '"' :: cs -> parseString tokens cs
 | ':' :: cs -> parseValue tokens cs
 | '}' :: cs -> tokens, cs
 ...

let rec parseValue tokens = function
 | c :: cs when Char.IsWhiteSpace(c) -> parseValue tokens cs
 | '{' :: cs -> parseObject tokens cs
 ...

That won't work, because parseObject doesn't know about parseValue. Can't reverse them either or I'd get the opposite problem. So what am I supposed to do here?

Brian
  • 117,631
  • 17
  • 236
  • 300
CodexArcanum
  • 3,944
  • 3
  • 35
  • 40

2 Answers2

11

You define mutually recursive function using the and keyword. Like this:

let rec parseObject tokens = function
 | '"' :: cs -> parseString tokens cs
 | ':' :: cs -> parseValue tokens cs
 | '}' :: cs -> tokens, cs
 ...

and parseValue tokens = function
 | c :: cs when Char.IsWhiteSpace(c) -> parseValue tokens cs
 | '{' :: cs -> parseObject tokens cs
 ...
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Ah! I didn't even know "mutually recursive functions" were a thing that you had to indicate. Haskell has spoiled me. Thank you so much, would have taken me forever to understand that was the problem otherwise. – CodexArcanum Oct 20 '10 at 22:01
3

Try replacing your second let rec with and to define a set of mutually recursive functions.

Joel Mueller
  • 28,324
  • 9
  • 63
  • 88