BradS2S
With-else and refactoring to pure functions
In your are working toward a true state machine and want to refactor code that isn’t comprised of pure functions, do you need to refactor with-else and if-else? If so, what’s the recommended best practice?
Also I was thinking this might be the case for “case” until I learned it was a macro for a group of functions.
Any assertions on my part have not been tested so please correct the premise of my question if I’m totally off-base.
Thanks!
Marked As Solved
sabiwara
Any of with, if and case can be used in pure functions without affecting their purity, just like conditionals like if or switch in other languages.
caseis not a macro but a special form: it gets compiled as an erlangcaseexpression (and it cannot introduce any side effect)- both
withandifare macros that get expanded ascaseat compile time, so there are literally the same thing in terms of resulting code
So when you write:
if foo() do
bar()
end
It is exactly the same as writing the code it would expand into:
case foo() do
x when x in [false, nil] -> nil
_ -> bar()
end
In this example, the purity of this expression only depends on the purity of foo/0 and bar/0.
Popular in Questions
Other popular topics
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








