Coursera’s Functional Programming Principles in Scala is just starting to get into gear, and I’m finding it difficult not to be disappointed by any language not named Erlang.
Pattern matching is just such a sweet way to handle branching and recursion. Anything else just looks so burdensome any longer.
During the lecture I watched tonight, the professor discussed Newton’s method of approximating square roots. Even his cleanest Scala version brought back too many bad memories of imperative programming languages.
Erlang, for all its flaws, will never be mistaken for Ruby. (Except Elixir, which I’m doing my best to avoid precisely because it’s trying to be Ruby on Erlang.)
-module(newton).
-compile([export_all]).
sqrt(X) ->
sqrt(X, mean(X, 1), X).
%% Base case: our current and previous guess are virtually
%% indistinguishable
sqrt(_X, Guess, Previous) when abs(Guess - Previous) < 1.0e-20 ->
Guess;
%% Otherwise, try again by dividing X by Guess and averaging
%% with Guess
sqrt(X, Guess, _Previous) ->
sqrt(X,
mean(Guess, (X / Guess)),
Guess).
mean(X, Y) ->
(X + Y) / 2.0.
And running, comparing with the math library:
136> newton:sqrt(4).
2.0
137> newton:sqrt(3.5).
1.8708286933869707
138> math:sqrt(3.5).
1.8708286933869707
139> newton:sqrt(24.999).
4.99989999899998
140> math:sqrt(24.999).
4.99989999899998
coursera
erlang
scala