4

I am learning Elixir and according to the linked book (page 64), the following function:

defmodule MyList do
  def square([]), do: []
  def square([ head | tail ]), do: [ head*head, square(tail) ]
end

should behave as follows:

MyList.square [4, 5, 6]
[16, 25, 36]

But when I plug it into my Elixir 1.2.0 installation on Ubuntu I get:

MyList.square [4, 5, 6]
[16, [25, [36, []]]]

What's happening here? Am I wrong or is the book wrong?

How do I get to the simple [16, 25, 36] ?

1 Answer 1

6

You have a small error in this line:

 def square([ head | tail ]), do: [ head*head, square(tail) ]

If we recurse at each step then the output is:

square([4, 5, 6])
[16, square([5, 6])]
[16, [25, square([6])]]
[16, [25, [36, square([])]]]
[16, [25, [36, []]]]

You want:

 def square([ head | tail ]), do: [ head*head | square(tail) ]

If we recurse at each step then the output is:

square([4, 5, 6])
[16 | square([5, 6])]
[16 | [25 | square([6])]]
[16 | [25 | [36 | square([])]]]
[16 | [25 | [36 | []]]]

Trying this in iex gives:

iex(3)> [16 | [25 | [36 | []]]]    
[16, 25, 36]
Sign up to request clarification or add additional context in comments.

2 Comments

oh brother - silly little syntax error. All makes sense now. BTW if I may add the speed with which I have received an answer to my (clearly silly) question reminds me of when I first learned Python - before it was fashionable - when the community was really responsive. Very excited about Elixir!
If you want to get more in touch with the community be sure to check the Elixir channel in Slack and the new Elixir forum (elixirforum.com) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.