Hi Everyone,
I am sure this has been asked hundreds of times, but i couldn’t find a simple toy example which demonstrated what i wanted to understand. To be clear this is more about coming to a functional paradigm from Python, JS/TS, etc.
When learning languages and frameworks i normally create a small contrived example for a Lirabry where you can add books, withdraw them, and so on. Phase 1 of this example is just adding books, in Python this is a super simple task and fits neatly into a class.
from typing import List
class Library:
name: str
books: List
def __init__(self, *, name: str, books: List):
self.name = name
self.books = books
def add_books(self, *, books: List):
self.books = [*self.books, *books]
library = Library(name="My Library", books=[])
print(library.__dict__)
library.add_books(books=["My Novel", "Some Book"])
print(library.__dict__)
library.add_books(books=["Moby Dick"])
print(library.__dict__)
I have not ported this straight to Elixir but rather i am trying to do this same task in Elixir, this is what i have currently (ignore my liberal use of pipe, it’s one of the things i really like about Elixir):
defmodule Library do
defstruct [:name, :books]
end
defmodule Library.Inventory do
def add_books(library, books) do
updated_stock = [books | library.books] |> List.flatten
%{library | books: updated_stock }
end
end
defmodule Main do
def main do
library = %Library{name: "My Library", books: ["Some Novel"]}
IO.inspect(library) # ["Some Novel"]
library = library |> Library.Inventory.add_books(["Moby Dick", "My Novel"])
IO.inspect(library) # ["Moby Dick", "My Novel", "Some Novel"]
end
end
Main.main()
My questions are:
- Is this functional? I know its a vague question, what i mean more is am i along the right track for a functional approach to this problem?
- How can my Elixir code be improved? Are there any glaring mistakes that i as a newbie have completely missed
- Do you know of any resources about building small practical examples such as this one?
Thanks a bunch!