If you want it inline then tuples are the traditional 'return multiple 
values from an expression (like if)' thing, and yes, this is the 
functionally traditional way of doing it.

{dataptr, data} = if dataptr < 0 do
  {0, tl data}
else
  {dataptr, data}
end


Moving it out into another function like the other posts is easy too, but 
honestly no point considering how short the requirement is and that it is 
likely not re-usable (if it is re-usable elsewhere, definitely move it out).

In general, keep functions simple, I try to keep them at no more than a few 
lines (I have many cases that I go over though), there is no harm on having 
lots and lots of defp functions as they get compiled together and optimized.


On Tuesday, August 23, 2016 at 6:51:22 AM UTC-6, Brian Bugh wrote:
>
> For fun and profit, I am writing a Brainf**k interpreter in Elixir.
>
> In one particular case, a data pointer should be decremented, and if it's 
> less than 0, it should be set to 0 and the top of the data stack should be 
> popped off.
>
> I assumed that I should write something like this (which passes my :
>
> dataptr = dataptr - 1
>
> if dataptr < 0 do
>   dataptr = 0
>   data = tl data
> end
>
> but I get a compiler warning when I do this. It suggested that I use the 
> assignment form of *if*, which is fine, but I can't find an elegant way 
> to write the code now. This is what I came up with, which seems uglier and 
> unnecessarily verbose for future readers. The first form above is much more 
> readable.
>
> [dataptr | data] = if dataptr < 0 do
>   [0 | tl data]
> else
>   [dataptr | data]
> end
>
> Is there a better Elixir-way to write this?
>

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-talk+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-talk/840c0bde-66e0-4ea8-abec-14d42840e67b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to