The Finnternet Like the Internet but with more me

Drink the Elixir: Tic Tac Toe String Matching

One of the first projects I did in Elixir was a multiplayer Tic Tac Toe game using Phoenix. I stored the board as a string with nine characters (a character for each spot on the board).

Spot definitions:

  • ”-“ = Open spot
  • “x” = Taken by X
  • “o” = Taken by O

After every move, the board state would have to be checked to see the state of the game. I implemented this check using one of Elixir’s strengths, string matching. This is a good example of how to use string matching because it shows how to match specific parts in a string which to me wasn’t obvious at first.

The important things to know for string matching are:

_                           // ignore everything else
<<_ :: size(8*numOfChars)>> // ignore numOfChars characters (assuming UTF-8)
str1 <> str2                // append str2 to str1

Using these three techniques, we can pattern match against specific spots in the board to determine which of the following states the game is in.

Possible game states:

  • “win_x” -> X won the game
  • “win_o” -> O won the game
  • “draw” -> Nobody won & the board is full
  • “o” -> O’s turn
  • “x” -> X’s turn

The game state update case statement:

case board do
  # Horizontal
  "xxx" <> _ -> "win_x"
  "ooo" <> _ -> "win_o"
  <<_ :: size(24)>> <> "xxx" <> _ -> "win_x"
  <<_ :: size(24)>> <> "ooo" <> _ -> "win_o"
  <<_ :: size(48)>> <> "xxx" -> "win_x"
  <<_ :: size(48)>> <> "ooo" -> "win_o"
  # Vertical
  "x" <> <<_ :: size(16)>> <> "x" <> <<_ :: size(16)>> <> "x" <> _ -> "win_x"
  "o" <> <<_ :: size(16)>> <> "o" <> <<_ :: size(16)>> <> "o" <> _ -> "win_o"
  <<_ :: size(8)>> <> "x" <> <<_ :: size(16)>> <> "x" <> <<_ :: size(16)>> <> "x" <> _ -> "win_x"
  <<_ :: size(8)>> <> "o" <> <<_ :: size(16)>> <> "o" <> <<_ :: size(16)>> <> "o" <> _ -> "win_o"
  <<_ :: size(16)>> <> "x" <> <<_ :: size(16)>> <> "x" <> <<_ :: size(16)>> <> "x" -> "win_x"
  <<_ :: size(16)>> <> "o" <> <<_ :: size(16)>> <> "o" <> <<_ :: size(16)>> <> "o" -> "win_o"
  # Diagonal
  "x" <> <<_ :: size(24)>> <> "x" <> <<_ :: size(24)>> <> "x" -> "win_x"
  "o" <> <<_ :: size(24)>> <> "o" <> <<_ :: size(24)>> <> "o" -> "win_o"
  <<_ :: size(16)>> <> "x" <> <<_ :: size(8)>> <> "x" <> <<_ :: size(8)>> <> "x" <> _ -> "win_x"
  <<_ :: size(16)>> <> "o" <> <<_ :: size(8)>> <> "o" <> <<_ :: size(8)>> <> "o" <> _ -> "win_o"
  # No winning case, check if draw
  _ -> if String.contains?(board, "-") do
      if (game.state == "x"), do: "o", else: "x"
    else 
      "draw"
    end
end

Fixing Poison Encode Error

In one of my Phoenix projects, I recently ran into the following error when attempting to return a struct returned from an Ecto query.

** (Poison.EncodeError) unable to encode value: {nil, "users"}

The reason for this error is because of the meta field included in the Ecto record struct. Thankfully this leads to a simple solution.

Add a derive annotation to your schemas and specify the fields you want to return.

@derive {Poison.Encoder, only: [:field1, :field2]}

Drink the Elixir: Using the With Construct

Coming from a background in imperative languages, I faced a few hiccups in my Elixir journey. One of the first logical differences I hit was a result of Elixir’s lack of early exits/returns.

Take the code below which is a common pattern in imperative code,

if (num <= 0)  {
	return "must be >0";
} 

if(num >= 5) {
	return "must be <5";
} 

return "valid input"

or alternatively using nested if/else

if (num <= 0)  {
	if(num >= 5) {
		return "valid input";
	} else {
		return "must be <5";
	}
} else {
	return "must be >0";
}

The first pattern cannot be done in Elixir and the second quickly leads to ugly, deeply nested code. You should instead use the with construct. As you can see in the functionally identical code below, there is a with block in which you declare multiple pattern matching clauses which if all passed, executes the do block and if any fail to match, executes the else block where pattern matching is done on the clauses there.

def inputTest(num) do
	with     {:ok}  <- gt_zero?(num),
		 {:ok}  <- lt_five?(num)
	do
		"valid input"
	else
		{:error, reason} -> reason
	end
end

def gt_zero?(num) do
	if num >= 0 , do: {:ok}, else: {:error, "must be >0"}
end

def lt_five?(num) do
	 if num <= 5, do: {:ok}, else: {:error, "must be <5"}
end

This pattern is flexible, reads well, and is a much better alternative to if/else craziness. I find myself using the with construct fairly often since it replaces the above patterns and I prefer its syntax over the pipe operator since you need to use a third party library to add error handling.

Toronto Roadtrip

Toronto cityscape

This past weekend I roadtripped to Toronto with a couple friends & stopped at Niagara Falls on the way back.

Trip Video

Aquarium

We left Boston at 4am and a short 9 hour drive later, found ourselves wandering around Toronto. Our Airbnb was right in downtown so we dropped our stuff off & headed to the aquarium.

Shark

Pretty sure I see a crack

The aquarium was much bigger & nicer than the Boston aquarium. It is kind of expensive at $35 per adult but worth going once. They had a cool moving walkway through a tunnel of sharks & whatnot. My favorite part of the aquarium was definitely the jellyfish wall.

Jellyfish

Spongebob would be in heaven

Other Toronto Stuff

Walking around Toronto, we happened upon some giant sign that would be very helpful if you happen to forget what city you are in. Continuing our walk, we found a ferry that leaving shortly for Toronto island so we decided to jump aboard. The island was bigger than we thought and we didn’t have a chance to explore it all but we saw some colorful houses & got a great view of the Toronto cityscape.

3D Toronto Sign

3D Toronto Sign

We also saw the hard to miss CN Tower. At the top section of the tower people could be seen doing the edge walk. As freaky as that sounded I was considering it but upon learning the price ($225!) I decided I would have to find a cheaper way to freak myself out.

CN Tower

CN Tower

There was one more thing we had to do before leaving Toronto. We would truly be remiss if we did not partake in one of Canada’s favorite pastimes. No I’m not talking about syrup chugging, moose riding, nor allowing ham to impersonate bacon. I am talking of course about hockey. We went to a Maple Leafs (why not Leaves?!!!) preseason game & although I do not fully understand hockey, it was a really good time.

Niagara Falls

On our way back we stopped in Niagara Falls. The falls were quite an impressive sight and the mist could be felt in the air once you got in the area.

That's a lot of water

That's a lot of water

Back Home

One weekend and 18 hours of driving later, I returned home sans my Canadian virginity & with a new eagerness to explore some of the country’s other spots.

Canadian strip club

Canadian strip club

Texas Roadtrip

Roadtrip map

My friend James invited me on a roadtrip to help move him, his fiancé Jackie, & their dog down to San Antonio. On the way we decided to spend a night in Virginia (at a friends house), Nashville, & New Orleans.

Trip Video

New Jersey

The first leg of the trip was to go to their apartment in New Jersey to pack up their apartment. We soon figured out that loading a U-Haul effectively is an art & it is an art that we weren’t very good at. We did manage to get most of the stuff in so I call that a win.

Basically what our U-Haul looked like

Basically what our U-Haul looked like

Virginia

One of our friends recently moved to Virginia with his fiancé so we visited them for a night. After a delicious homecooked meal, we went to the movies to see the It. Although the movie was mehhh, it ended up spurring a trip full of It jokes, listening to the audio book, & the rewatching of the original mini-series.

James trying to get kidnapped by Pennywise

James trying to get kidnapped by Pennywise

Nashville

A day of driving later, we ended up in Nashville. We got there pretty late at night & had to leave early in the morning so we only had time to do one thing, arguably the most important thing, eat BBQ!

My BBQ date

My BBQ date

New Orleans

Another long day of driving landed us in New Orleans just in time to go to bed. The next morning we got brunch & walked around the city for a bit before making a making our way to Texas.

Nice & colourful

Nice & colourful

Texas

Our first stop in Texas was Houston where stopped for dinner at an ice house which is apparently unique to Texas & is basically an open air bar. From there we headed to Jackie’s family house in Hondo. Jackie’s family live in a ranch style house complete with two horses, a tractor, & a whole bunch of piglets.

#farmlife

#farmlife

We stayed with her family for a couple of nights then drove toward her brother’s house in Midlothian – a quaint city south of Dallas. All this driving through Texas made me realize how big, flat, & full of copy & paste house communities the state is.

My first puffy tacos!

My first puffy tacos!

The last couple days of the trip we spent exploring San Antonio. I really liked the city, from it having the historical Alamo on a random city block to the riverwalk cutting through the city. The riverwalk is one of my favorite city features that I have seen on my travels. Lined with restaruants, bars, & clubs, it is a scenic and fun place to hangout.

I present to you the Alamo

I present to you the Alamo

The Riverwalk

The Riverwalk

Back Home

Thankfully the trip was a one way roadtrip & I flew back home. Texas was awesome & I’m glad I have someone to visit down there because I definitely want to go back soon.

Where all the muscleheads live

Where all the muscleheads live