Java VM上で動作するスクリプト言語Groovyをいじってみました。Rubyの影響を強く受けたのか,JavaとRubyを合わせたような言語使用でした。以下のコードは複素数の計算プログラムです。
Groovy公式サイト : http://groovy-lang.org/
#!/bin/bash
source=complex.groovy
cat > $source << EOF
groovy $source
if [ -e $source ]; then
rm -f $source
fi
source=complex.groovy
cat > $source << EOF
class Complex
{
double re
double im
Complex(re, im)
{
this.re = re
this.im = im
}
Complex plus(c)
{
new Complex(re + c.re, im + c.im)
}
Complex minus(c)
{
new Complex(re – c.re, im – c.im)
}
Complex multiply(c)
{
new Complex((re * c.re – im * c.im), (re * c.im + im * c.re))
}
Complex div(c)
{
def denom = (c.re ** 2) + (c.im ** 2)
new Complex((re * c.re + im.c.im) / denom, (im – im * c.re) / denom)
}
String toString()
{
re + (im >= 0 ? ‘+’ : ”) + im + ‘i’
}
boolean equals(Complex c)
{
re == c.re && im == c.im
}
}
a = new Complex(3, 1)
b = new Complex(4, -2)
assert a + b == new Complex(7, -1)
assert a * b == new Complex(14, -2)
c = new Complex(1, 1)
c += a
assert c == new Complex(4, 2)
println a
println b
println c
EOF{
double re
double im
Complex(re, im)
{
this.re = re
this.im = im
}
Complex plus(c)
{
new Complex(re + c.re, im + c.im)
}
Complex minus(c)
{
new Complex(re – c.re, im – c.im)
}
Complex multiply(c)
{
new Complex((re * c.re – im * c.im), (re * c.im + im * c.re))
}
Complex div(c)
{
def denom = (c.re ** 2) + (c.im ** 2)
new Complex((re * c.re + im.c.im) / denom, (im – im * c.re) / denom)
}
String toString()
{
re + (im >= 0 ? ‘+’ : ”) + im + ‘i’
}
boolean equals(Complex c)
{
re == c.re && im == c.im
}
}
a = new Complex(3, 1)
b = new Complex(4, -2)
assert a + b == new Complex(7, -1)
assert a * b == new Complex(14, -2)
c = new Complex(1, 1)
c += a
assert c == new Complex(4, 2)
println a
println b
println c
groovy $source
if [ -e $source ]; then
rm -f $source
fi
