Accessing pattern matched variable in a different function

Hi @allgeo , let’s take the lessons from Iterating over a list with a certain condition (sorry, I am very new to functional programming) - #7 by BartOtten and apply this to your question from this topic.

Your list is bound to the variable list in Elixir in function1(). There you pattern match the elements of the list, so you get first_word, second_word, third_word variables with are 3 memory address bindings _within the scope of function1 (#memory_address1, #memory_address2, #memory_address3). There is NO way function2 knows the memory addresses function1 used for those variables.

In Elixir the last thing in a function is the result from that function. If you apply that to function1() you’ll see that function1 will return a list which is equivalent to [value of #memory_address1, value of #memory_address2, value of #memory_address3] which happens to be [Peanut, Butter, Cookies] and is exactly the same as the list you put into the function.

How can we let function2 know about the memory addresses used in function1? We can’t. What we can do is bind the result to a new variable (which will be in the scope outside the function, and pass that variable into function2.

In long form:

main_result = main([first_word, second_word, third_word])
function2_result = function2(main_result)
end_result = function2_result

main_result is bound in the global scope, so it can be passed into function2()
function2_result is bound in the global scope, so it can be assigned to variable end_result

In short form:
As using temporary variables is ugly, Elixir has a nice trick. You can pipe |> the result of a function into the next function. In the example could be written as;

end_result = 
   main()
   |> function2()

Which elixir sees as:

end_result = 
   main()
   |> function2(take the result from before the `|>` and use it as variable `list`)