3 ms·
That's great! I very briefly went through the introductory docs, but otherwise I just dove right in. The language is really simple, the tough part is wrapping y
by marcus_cemes 5y ago
That's great! I very briefly went through the introductory docs, but otherwise I just dove right in. The language is really simple, the tough part is wrapping your head about immutability.
There's an awesome repo with examples in pretty much every language [1], I go there afterwards to learn how other people did it. It's amazing to see so many different ways of approaching the problem. My solutions are also public [2], but bear in my I'm still only a few days in to learning Elixir!
If you do want to try attacking AoC with Elixir, I suggest you research and understand these concepts, it's more than enough to get you going:
- Pattern matching. The "=" sign is _not_ an assignement, it's trying to fill the shape of the variables on the left with the stuff on the right.
- The pipe operator "|>", the return value of the previous function is implicitly as the first paramter of the next function, it makes it easy to build chains.
- There is no "return". Use small functions with `case` statements, or function overloading. The last value in a function is implicitly the return value, like in Rust.
- Enum.map(), filter(), reduce(), zip(), chunk(), these functions largely get you through the manipulation of data. The first three are very popular in JS.
- Immutability. There's no mutating data, hence why you need reduce() for example.
- There are no loops, instead, get used to doing recursion. hd(), tl() are useful for this.
- Anonymous functions `fn a, b -> a + b end`, there is also a shorthand form `&(&1 + &2)`, and you can also pass functions by reference `&sum/2`
- The "/1", "/2", ... after a function is the arity, it's not scary, it just means the number of paramters that it takes.
- Function overloading is amazing, it's like pattern matching. If you provide constants in the function declaration, it will only be called if those constants match:
```
def factorial(0), do: 1
def factorial(n) when n > 0, do: n * factorial(n - 1)
```
I find the above really elegant. It's correct, the special case for "0" is very explicit, and if you try a negative number, Elixir will simply be unable to match the given problem to a function definition (n < 0), which makes more sense than throwing "BadArgument" errors/exceptions.
If you really want to just solve problems, I advise sticking with Python, there's nothing wrong with it. Most languages also provide a lot of functional concepts, I'm sure Python is no exception (with some libraries). Be prepared that functional languages require you to think differently, but it is really fun to do things in a functional way!
Good luck!
[1]: https://github.com/Bogdanp/awesome-advent-of-code https://github.com/Bogdanp/awesome-advent-of-code
[2]: https://github.com/MarcusCemes/advent-of-code-2021 https://github.com/MarcusCemes/advent-of-code-2021