Subscribe now

Elixir Weekly Drip #2 and Exercise: Reverse Polish Notation Calculator [02.13.2017]

This week's links cover a few things we didn't have a chance to go over yet in great detail:

  • Documentation
  • Control Structures
  • The with Special Form
  • More details from Enum

After the links, you'll find an exercise to build a Reverse Polish Notation calculator as a process.

Exercise

This week we'll build a process that serves as a Reverse Polish Notation Calculator. That's a pretty nebulous exercise to throw out at you, so I've devised some tests you should make pass. You can check out this tag from this repository for a good starting point. It has some tests in it that you should make pass:

defmodule RpnTest do
  use ExUnit.Case

  test "starts with an empty stack" do
    {:ok, pid} = Rpn.start
    assert Rpn.peek(pid) == []
  end

  test "pushing onto the stack" do
    {:ok, pid} = Rpn.start
    Rpn.push(pid, 5)
    assert Rpn.peek(pid) == [5]
    Rpn.push(pid, 1)
    assert Rpn.peek(pid) == [1, 5]
  end

  test "adding" do
    {:ok, pid} = Rpn.start
    Rpn.push(pid, 5)
    Rpn.push(pid, 1)
    Rpn.push(pid, :+)
    assert Rpn.peek(pid) == [6]
  end

  test "subtracting" do
    {:ok, pid} = Rpn.start
    Rpn.push(pid, 5)
    Rpn.push(pid, 1)
    Rpn.push(pid, :-)
    assert Rpn.peek(pid) == [4]
  end

  test "multiplying" do
    {:ok, pid} = Rpn.start
    Rpn.push(pid, 5)
    Rpn.push(pid, 2)
    Rpn.push(pid, :x)
    assert Rpn.peek(pid) == [10]
  end

  test "wikipedia example" do
    {:ok, pid} = Rpn.start
    Rpn.push(pid, 5)
    Rpn.push(pid, 1)
    Rpn.push(pid, 2)
    Rpn.push(pid, :+)
    Rpn.push(pid, 4)
    Rpn.push(pid, :x)
    Rpn.push(pid, :+)
    Rpn.push(pid, 3)
    Rpn.push(pid, :-)
    assert Rpn.peek(pid) == [14]
  end
end

Going through this exercise myself was a ton of fun. I hope you enjoy it and you learn a lot. Make sure to just work from the top to the bottom, making one test pass at a time. In the next episode, I'll provide my solution, which I test-drove through the exact same series of tests. See you soon!