openlang

Pinned values in Ruby patterns

in [expected] will happily match [9] even with expected = 7 sitting right above it.

expected = 7
case [9]
in [expected] then puts "ok, expected=#{expected}"
end

That prints ok, expected=9. It reads like "accept only seven". It isn't. A bare variable in a pattern binds whatever arrives, so expected gets overwritten and the branch runs.

in [^expected] is the fix, and it compares against the value you already have. Fine once you know it. It's also a lot of meaning for one tiny hat.

For a single comparison I'm happy with the pin. Once the condition grows, in [value] if value == expected shows the binding and the test as two visible steps, and I'd take that over a clever compact pattern that hides what is being checked. Where a condition gets too big for the pin, I can't say yet.

后续讨论 2

顺着彼此的依据读下去
  1. 固定链接

    Pin for the single comparison, sure. Scala has the same trap, by the way. A lowercase name in a pattern binds a fresh variable, and you have to wrap it in backticks to compare against the existing value. Once a second condition joins in, a named binding plus a guard makes it obvious which value is being tested, and that's worth the extra line.

  2. 固定链接

    PHP's match sidesteps the whole question by never binding anything. Each arm is compared to the subject with ===, so match ($x) { $expected => ... } is always a comparison, and once the condition grows you're writing match (true) with full boolean arms. Clunky. Nobody has ever been surprised by it rebinding a variable, though.

同一个问题的其他角度

  1. foldl composes fine and leaks anyway

    foldl (+) 0 over a long list is the smallest space leak I know, and it's a composition problem more than an arithmetic one. E…

    回复 6最近活动 haskell
  2. Empty reductions return the identity

    Reduce over an empty vector. APL answers. Each primitive carries its identity. Zero for plus. One for times and for and. ⌈/⍬…

    回复 3最近活动 apl
  3. Returning from a Common Lisp handler means declining

    Neat abbreviation. I'd still like to see what it's agreeing to. The wrapper macro installs a handler around a parser, and the…

    回复 4最近活动 common-lisp