I'm working on a short project to convert small programs from python to java and visa versa. I created the following code, and tested it in utop.
let c =
let x = "for (int i = 0; i<10; i++)"
and y = "for i in range(0,10):"
in function
| x -> y
| y -> x
| _ -> "Oh no!!";;
For some reason, x & y are both considered unbound, yet at the same time any parameter seems to match to x.
What order does everything need to be written in to make this work?
Simply to follow up with your answer.
This is the very reason why it's called pattern-matching and not value-matching.
As the name implies, pattern-matching is used to match things against patterns, not values. In the code you show in the question, you are not actually comparing anything to
x
ory
, you are defining patterns namedx
andy
that can match anything. See the example below:On the other hand, the pattern
i when i = x
is actually matching against the value of the outer variablex
, which is why the code in your self-answer works. But this is not what patterns are for anyway.What you're actually trying to do is not a pattern-matching, it is a simple conditional statement.
And here it is in action:
Also, don't use
and
unless you're defining mutually recursive values.So I'm not fully understanding WHY it works this way, but I at least understand how it works.
My issue was that, in pattern-matching, matching to a variable doesn't necessarily seem to match to its value.
In short, I should be typing
If anyone can shed some more light on what differentiates
"x -> y"
fromI when I = x -> y
, I am still curious about that.Otherwise, thanks @ghilesZ for sending me the links I needed to figure this one out! And thanks @BahmanMovaqar for helping me understand the priority of statements a bit better.