2016年6月9日木曜日

開発環境

Seven More Languages in Seven Weeks (Bruce Tate (著)、Ian Dees (著)、Frederic Daoud (著)、Jack Moffitt (著)、Pragmatic Bookshelf)のChapter 3(Elixir)、Day 1(Laying a Great Foundation)、Do (Hard)(No. 4229).を取り組んでみる。

Do (Hard)(No. 4229)

コード(Emacs)

#!/usr/bin/env elixir

defmodule Tree do
  def traverse(tree) do
    traverse(tree, 0)
  end
  def traverse({node, {left, right}}, indent) do
    IO.write replicate_space(indent)
    IO.puts "#{node}"
    traverse(left, indent + 2)
    traverse(right, indent + 2)
  end
  def traverse(node, indent) do
    IO.write replicate_space(indent)
    IO.puts "#{node}"
  end
  
  def replicate_space(n) do
    if n == 0 do
      ""
    else
      " #{replicate_space(n - 1)}"
    end
  end
end

Tree.traverse("SeeSpot.")
IO.puts ""
tree = {"See Spot.", {"See Spot sit.", "See Spot run."}}
Tree.traverse(tree)
IO.puts ""
Tree.traverse({"See spot", {tree, {"See spot", {tree, "See spot"}}}})

入出力結果(Emacs, Terminal, elm repl)

$ ./hard.exs
SeeSpot.

See Spot.
  See Spot sit.
  See Spot run.

See spot
  See Spot.
    See Spot sit.
    See Spot run.
  See spot
    See Spot.
      See Spot sit.
      See Spot run.
    See spot
$    

0 コメント:

コメントを投稿

Comments on Google+: