The first definition of x is masked by the next definition of x.
However, I don’t like this because the meaning of x changes inside the code fragment.
It’s like in the real world you meet someone called Xavier Leroy, then on the same day you
meet someone else who also claims he is also named Xavier Leroy.
While this would be possible, this would be annoying.
Is the following better practice or is there an even better way:
let x = something in
let x = `Do_not_use_further in
let y = something_else in
What I am trying to do is to voluntarily put x out of scope so that
it is not mistakenly used further down in the same function.
For your specific example, I would argue that using x as a (reused) variable name is a problem in itself.
But on the general idea, Erlang for example has no concept of variable rebinding; variable names can only be bound once in the same scope. Elixir, however, like OCaml, allows rebinding variables. I felt Elixir’s behavior is a feature rather than a bug.
Perhaps just put it under an inner scope? e.g.
let _ =
let x = ... in
...
in
... (* x is not visible here *)
That said, I think it’s more trouble with little benefit, but I might be wrong and you might have a valid use case.
It’s like in the real world you meet someone called Xavier Leroy, then
on the same day you
meet someone else who also claims he is also named Xavier Leroy.
So, like attending a modern danse event and then an OCaml meeting?
I tend to use variable rebinding heavily. One reason is, as you pointed out, to avoid using “stale” variables. Another reason is, although maybe a bit controversial, making the code appear imperative, say
let x = x + 1 in
let x = x + 1 in
x
This makes the code pleasant to the people who is used to imperative coding style.
Of course, if you really change the intended meaning of x, you should change the name.
As you write it, the first x is something and the y does not use it, so why use the let … in construction in this case? That doesn’t sound natural: “let x be something in… and don’t use it”.
What’s the purpose of computing x if it is not used? Is it just for some kind of side effect, in which case, the let binding is useless?