2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

概要

paiza.ioでelixirやってみた。
練習問題やってみた。

練習問題

Agentを使わないで、Forthインタープリタを書け。

サンプルコード


defmodule Main do
    def add(stack) do
	    po = length(stack) - 2
	    top = List.last(stack)
		stack = List.update_at(stack, po, &(&1 + top))
		stack = List.delete_at(stack, po + 1)
	end
	def sub(stack) do
		po = length(stack) - 2
		top = List.last(stack)
		stack = List.update_at(stack, po, &(&1 - top))
		stack = List.delete_at(stack, po + 1)
	end
	def mul(stack) do
		po = length(stack) - 2
		top = List.last(stack)
		stack = List.update_at(stack, po, &(&1 * top))
		stack = List.delete_at(stack, po + 1)
	end
	def div(stack) do
		po = length(stack) - 2
		top = List.last(stack)
		stack = List.update_at(stack, po, &(&1 / top))
		stack = List.delete_at(stack, po + 1)
	end
	def dup(stack) do
		top = List.last(stack)
		stack ++ [top]
	end
	def drop(stack) do
		po = length(stack) - 2
		stack = List.delete_at(stack, po + 1)
	end
	def get(stack) do
		List.last(stack)
	end
	def push(stack, n) do
		{v, _} = Integer.parse(n)
		stack ++ [v]
	end
    def run(str) do
        Enum.reduce(String.split(str, " "), [], fn s, stack ->
            cond do
	        s == "+" ->
		        stack = add(stack)
	        s == "-" ->
		        stack = sub(stack)
	        s == "*" ->
		        stack = mul(stack)
	        s == "/" ->
		        stack = div(stack)
	        s == "dup" ->
		        stack = dup(stack)
	        s == "drop" ->
		        stack = drop(stack)
	        s == "." ->
		        IO.inspect get(stack)
	        true ->
                stack = push(stack, s)
            end
        end)
    end
end

Main.run("9 9 - 9 9 / .")
Main.run("9 9 / 9 9 / + .")
Main.run("9 9 + 9 + 9 / .")
Main.run("9 9 9 + 9 / dup + .")
Main.run("9 9 9 + 9 / dup + - .")
Main.run("9 dup 9 + 9 + 9 / - .")
Main.run("9 9 9 + 9 / - .")
Main.run("9 9 9 drop 9 / - .")
Main.run("9 9 - 9 * 9 + .")
Main.run("9 9 / 9 dup 9 / + .")
Main.run("9 9 9 + 9 / + .")
Main.run("9 dup 9 9 + + 9 / + .")
Main.run("9 9 9 + 9 / dup + + .")
Main.run("9 dup 9 9 + 9 / dup + - + .")
Main.run("9 dup dup 9 + 9 + 9 / - + .")


実行結果

1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9
10.0
11.0
12.0
13.0
14.0
15.0

成果物

以上。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?