Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reorder these F# functions to make sense?

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?

like image 642
CodexArcanum Avatar asked Dec 09 '22 13:12

CodexArcanum


1 Answers

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
 ...
like image 126
sepp2k Avatar answered Dec 18 '22 05:12

sepp2k