Ok, here’s my erlang take on Section 1.1.4 of SICP, or you can go look at my Ruby or Factor versions.
Unlike Scheme, Ruby, or Factor, I’ve got to put the code for the square and sum_of_squares functions1 into a separate file. I’m not going to explain the mechanics of the file, but we can take a look at the functions themselves.
sicp.erl-module(sicp).
-export([square/1]).
-export([sum_of_squares/2]).
square(A) -> A * A.
sum_of_squares(A, B) -> sicp:square(A) + sicp:square(B).
square has an arity of 1 (it takes a single argument), and returns the value of that argument times itself. Because mulitplication only works with numeric types, it will work for integers and floats, but will fail for non-numeric arguments.
To execute these functions we need to compile the code (see line 1 below). Then we just call the function (with its module namespace) and give it an appropriate argument.
1> c(sicp).
{ok,sicp}
2> sicp:square(5).
25
3> sicp:sum_of_squares(3,4).
25
And that’s about all there is to it. Pretty simple stuff. Next up will be section 1.1.6 exercise 1.3.
1 In SICP they’re called procedures; in Ruby, methods; and in Factor, words. I just need to try to keep them all straight.
No comments:
Post a Comment