A big smile appeared on my face tonight after typing the following:
-module(math1). -export([factorial/1]). factorial(0) -> 1; factorial(N) -> N * factorial(N-1). def factorial(n) return 1 if n == 0 n * factorial(n-1) end Maybe not so obvious. But check this out:
-module(temp). -export([convert/2]). convert({fahrenheit, Temp}, celsius) -> {celsius, 5 * (Temp -32) / 9}; convert({celsius, Temp}, fahrenheit) -> {fahrenheit, 32 + Temp * 9 / 5}; convert({reaumur, Temp}, celsius) -> {celsius, 10 * Temp / 8}; convert({celsius, Temp}, reaumur) -> {reaumur, 8 * Temp / 10}; convert({X, _}, Y) -> {cannot,convert,X,to,Y}. This a simple temperature conversion program. Done in Ruby with methods, although not normally the way that I would introduce such functionality into a program:
def convert(from, temp, to) case to when :celsius : to_celsius(from, temp) when :fahrenheit : to_fahrenheit(from, temp) when :reaumur : to_reaumur(from, temp) else "cannot convert #{from} to #{to}" end end def to_celsius(from, temp) case from when :fahrenheit : 5.0 * (temp - 32.0) / 9.0 when :reaumur : 10.0 * temp / 8.0 when :celsius : temp else "cannot convert #{from} to celsius" end end def to_fahrenheit(from, temp) case from when :celsius : 32.0 + temp * 9.0 / 5.0 when :fahrenheit : temp else "cannot convert #{from} to fahrenheit" end end def to_reaumur(from, temp) case from when :celsius : 8.0 * temp / 10.0 when :reaumur : temp else "cannot convert #{from} to reamur" end end Yikes! The pattern matching in Erlang functions really comes in handy. Here is the output from both terminals (Erlang then Ruby):
...