TomD
TomD

Reputation: 9

recursive pattern match with options

When you are patterning matching in OCaml and returning an option type, you make your pattern return a Some x or None. If your pattern returns the function (recursively), would you need to put Some in front of it? Let me make this more clear:

example code:

let rec whatt (c: coding) : bool option = 
match c with
|a(a) -> Some a
|b(b) -> None
|d(x,s,l) -> Some whatt x and Some whatt s and Some whatt l 

I'm not sure A.) if you'd need Some because of some value you're getting and putting back into the function and B.) I'm not sure the syntax of separating the returned values in the last line. And, &&, || ?

Upvotes: 0

Views: 232

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

OK, well the "and" operator in OCaml is &&. Since its arguments are bool and not bool opt, you can't have an expression Some x && Some y.

Furthermore, your function whatt (by hypothesis) returns a bool opt already. So you don't need to apply Some to it to get a bool opt. In other words Some (whatt x) has the type bool opt opt, which is ever farther from working.

Third, you need to decide what you want the value of your result to be if whatt returns None. Let's say you want to treat both Some false and None as effectively false. Then you could write something like this:

let bvalue = function Some b -> b | None -> false

bvalue (whatt x) && bvalue (whatt s) && bvalue (whatt l)

This is probably not exactly what you're looking for but maybe it will give you some ideas.

Upvotes: 1

Related Questions