4 ms·
I think the real question we all want to know is why lambdas don't have "do"
by throwawaymaths 3y ago
I think the real question we all want to know is why lambdas don't have "do"
- sodapopcan 3y agoLambad definitions don't take arguments, they jump straight to argument matching. Take: case value do true -> "true" false -> "false" _ -> "uh..." end vs fn true -> "true" false -> "false" _ -> "uh..." end `do` is simply syntactic sugar for a keyword list argument containing a `:do` key: if(true, [{:do, "hi there"}]) So it wouldn't make sense for `fn` to take a `do`.
- throwawaymaths 3y agofn do true -> "true" false -> "false" _ -> "uh..." end
- sodapopcan 3y agoAs much as I despise people responding in pure code, you're right, it's technically `fn/1` [0]. Even though the docs say `fn(clauses)`, `cond/1`, which requires the `do`, also says `cond(clauses)` [1] so looks like I'm wrong. [0] https://hexdocs.pm/elixir/1.14/Kernel.SpecialForms.html#fn/1 https://hexdocs.pm/elixir/1.14/Kernel.SpecialForms.html#fn/1 [1] https://hexdocs.pm/elixir/1.14/Kernel.SpecialForms.html#cond/1 https://hexdocs.pm/elixir/1.14/Kernel.SpecialForms.html#cond...
- josevalim 3y agoBecause `do` binds the farthest away. In these examples: case some_fun(1) do end case some_fun() do end case some_fun do end We all know `do` binds to case. Therefore, if `fn` used `do`, the `do` would bind to the farthest call to: # this code Enum.map list, fn do end # or this code map list, fn do end would both bind `do` to `map`. Of course we could special case `fn do` but having `do` bind to different places based on `fn` would be extremely confusing.
- throwawaymaths 3y agoDoes anybody actually call Enum.map without parentheses? That's actively discouraged currently. Enum.map(list, fn do _ -> :ok end) Is unambiguous Honestly I do appreciate not having to type two characters, but I'm currently onboarding a bunch of n00bs and they're very puzzled by this one inconsistency
- sodapopcan 3y agoWell, I didn't have much luck last time I responded to you, but I'll try again since you haven't gotten a response yet! Regardless of whether or not it's actively discouraged, it still must be supported since Elixir is so heavily bootstrapped. Since `defmodule`, `def`, etc are all just macros written in Elixir, there are no special rules around which functions/macros are allowed to be called without parens. There was some discussion about that on the forums a while ago (like requiring parens for functions and not for macros) and the answer is that that will never happen.
- throwawaymaths 3y agoWell I mean it wouldn't have been a big deal, if the do block binds to the outermost, then in most cases just would get a compiler error since usually a private fn/0 doesn't exist. Still though in the early days elixir more strongly preferred no-parens, so avoiding that is understandable.
- sodapopcan 3y agoTrue!