marick
Is `Function.constantly` worth adding?
I confess I don’t use Function.identity because &(&1) comes to mind faster. However, there’s another function that seems commonly used in functional languages, which is a function that makes a function that always returns the same value:
def constantly(value) do
fn _ -> value end
end
Given there’s no shorter version than fn _ -> value end (is there?) would it be worth adding Function.constantly?
Most Liked
OvermindDL1
“Other languages” have this function also seem to be the same languages where every function is arity 1 (what you’d think of as an arity 3 function is just an arity 1 that returns a function that is arity 1 that returns a function that is arity 1 that return the result), and no language on the BEAM can work quite like that without a huge amount of preprocessing to ‘pack’ arity’s together if you want to work with the rest of the beam.
benwilson512
I think this proposal is tricky because, unlike identity/1, there isn’t an obvious arity that your return function should have. Should it be:
fn -> value end
or
fn _ -> value end
or
fn _, _ -> value end
... etc
Each of those has real scenarios where they’d be useful.
The other issue is that these two things do not have the same semantics: Function.constantly(code) and fn -> code end will behave differently depending on what code is. If code is DateTime.utc_now() then Function.constantly will return the same date time over and over, but fn -> DateTime.utc_now() end will return a new datetime each time it is invoked.
al2o3cr
Nitpick: Function.constantly(value) is also not a shorter version, since it’s literally nine characters longer.
Last Post!
marick
Clojure has a constantly, and it has functions that aren’t just syntactic sugar for arity-1 functions.
Popular in Discussions
Other popular topics
Chat & Discussions>Discussions
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









