Whitespace実装用のスタック
30分プログラム、その502。最近、Whitespaceとかbrainfuckとかの難読言語が流行っているらしいので、ボクもWhitespaceを実装してみようと思う。というわけで、まずはスタックを実装してみた。
wikipedia:Whitespaceに載っていた5つのスタック操作は実装してみた。
- push: 数値をスタックに積む
- dup: スタックの1番上を複製する
- dup_n: スタックのn番目をコピーして一番上に積む
- swap: スタックの1番目と2番目を交換する
- pop: スタックの1番上を物を捨てる
使い方
# stackを作る my $stack = Stack->new; # 3つほど数字をpushする $stack->push(42)->push(1)->push(0); # 先頭を複製して、pushする $stack->dup; # 先頭を削除する $stack->pop;
ソースコード
#! /usr/bin/perl # -*- mode:perl; coding:utf-8 -*- # # whitespace-stack.pl - whitespace実装用のstack # # Copyright(C) 2009 by mzp # Author: MIZUNO Hiroki / mzpppp at gmail dot com # http://howdyworld.org # # Timestamp: 2009/01/03 22:23:06 # # This program is free software; you can redistribute it and/or # modify it under MIT Lincence. # use strict; use warnings; use Data::Dumper; package Stack; sub new{ my ($class) = @_; bless([],$class); } sub push{ # push integer my ($self,$n) = @_; push @$self,$n; $self; } sub dup{ # duplicate a top of stack my ($self) = @_; $self->push($self->[-1]); } sub dup_n{ # duplicate n-th of stack my ($self,$n) = @_; my $val = $self->[-$n]; $self->push($val); } sub swap{ # swap 1-st of stack and 2-nd of stack my ($self,$n) = @_; my $first = $self->[-1]; my $second = $self->[-2]; $self->[-1] = $second; $self->[-2] = $first; $self; } sub pop{ # remove a top of stack my ($self,$n) = @_; pop @$self; $self; } package main; my $stack = Stack->new; $stack->push(42)->push(1)->push(0); print Dumper($stack); $stack->dup; print Dumper($stack); $stack->pop; print Dumper($stack);