2

I am reading "Programming Elixir 1.3" (PragPub) and ran across something that doesn't make much sense to me. On page 42 the author describes closures pointing out that in

greeter = fn name -> (fn -> "Hello #{name}" end) end 

the returned function 'remembers' the value of the provided name parameter. This is the nature of closures. However, 2 pages later he gives the following example:

defmodule Greeter do def for(name, greeting) do fn (^name) -> "#{greeting} #{name}" (_) -> "I don't know you" end end end 

I don't understand why the name identifier is pinned in the first function head since it should have the value passed in 'remembered' as part of the closure.

1 Answer 1

3

This is so that it matches on the value of what's contained in name, rather than doing a pattern match and rebinding to a new variable called name.

Checkout the documentation for the pin operator, that hopefully helps explain it a bit better.

Sign up to request clarification or add additional context in comments.

3 Comments

I read that already, but I don't see the relationship. In the documentation, the pattern matching is done by matching the left side with what is on the right side of the match operator. Are you saying that, without the pin operator, we would be throwing away the value of name passed to the for function?
In essence yes. It'll be equivalent to creating a new variable called name in the inner scope which will take the value of whatever was passed into that function. Think of it in terms of what would happen if the variable was named something else at that point. It would still match by taking the value passed in. Hope that makes sense?
OK. I was looking at the problem wrong. In the first example, the value of name was never re-bound through a pattern match so the value was maintained in the closure. In the second example, the value of name was rebound to whatever value was passed into the anonymous function due to the pattern matching of the two functions definitions. This is what is forcing us to use the pin operator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.