I recently started learning Elixir. Coming from an object oriented programming background I am having trouble understanding Elixir functions.
I am following Dave Thomas's book Programming Elixir >= 1.6, but I do not quite understand how functions work.
In the book, he has the following example:
handle_open = fn
{:ok, file} -> "Read data: #{IO.read(file, :line)}"
{_, error} -> "Error: #{:file.format_error(error)}"
end
handle_open.(File.open("code/intro/hello.exs")) # this file exists
-> "Read data: IO.puts \"Hello, World!\"\n"
handle_open.(File.open("nonexistent")) # this one doesn't
-> Error: no such file or directory"
I do not understand how the parameters work. Is there an implicit if, else statement hidden somewhere?
There are a couple of things going on here, and I'll try to cover all of them. For starters, there are two different functions being used here. One is the named function (File.open) and the other one is an anonymous function you created, assigned to the variable handle_open. There's a slight difference in the way both are called.
When you call the File.open function inside the handle_open function it, basically means you are calling handle_open on its result.
But the File.open/2 function itself can return two values:
{:ok, file} if the file exists{:error, reason} if it doesn't (or if there's another error)The handle_open function uses pattern matching and multiple function clauses to check what the response was and returns the appropriate message. If the given value "matches a specified pattern" it executes that statement, otherwise it checks against the next pattern.
Though in a sense, it is similar to an if-else statement, a better analogy is the case keyword:
result = File.open("/some/path")
case result do
{:ok, file} ->
"The file exists"
{:error, reason} ->
"There was an error"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With