Benjamin Halsted // [bgh] todo, add something clever here.

16Mar/100

Erlang Programming Exercise: 3-3

Side Effects is the title of exercise 3-3. Is printing to stdout a side effect? It must be since it makes a permanent change to the system. I just hadn't considered that before.

After the first couple of exercises, this one is a bit easier and gives you a little pat on the back. Enjoy feeling smart for a couple minutes, exercise 3-8 is around the corner.

Here are the two parts for this exercise:

Write a function that prints out the integers between 1 and N.
Write a function that prints out the even integers between 1 and N.

-module(threethree).
-export([print_count/1, print_even_count/1]).

print_number(Number) ->
	io:format("Number:~p~n", [Number]).

print_count(End, End) ->
	print_number(End);
print_count(Current, End) ->
	print_number(Current),
	print_count(Current+1, End).

print_count(Num) when Num > 0 ->
	print_count(1, Num).

print_even_number(Number) when Number rem 2 == 0 ->
	print_number(Number);
print_even_number(_Number) ->
	ok.

print_even_count(End, End) ->
	print_even_number(Current);
print_even_count(Current, End) ->
	print_even_number(Current),
	print_even_count(Current+1, End).

print_even_count(Num) when Num > 0 ->
	print_even_count(1, Num).

I didn't refactor this code until I went to post it. My guards are on the print function, so I re-use the incrementing loop and pass in which print function I want to use:

-module(threethree_ref).
-export([print_count/1, print_even_count/1]).

print_number(Number) ->
	io:format("Number:~p~n", [Number]).

print_even_number(Number) when Number rem 2 == 0 ->
	print_number(Number);
print_even_number(_Number) ->
	ok.

print_count_loop(Print, End, End) ->
	Print(End);
print_count_loop(Print, Current, End) ->
	Print(Current),
	print_count_loop(Print, Current+1, End).

print_count(Num) when Num > 0 ->
	print_count_loop(fun print_number/1, 1, Num).

print_even_count(Num) when Num > 0 ->
	print_count_loop(fun print_even_number/1, 1, Num).

Here it is in action:

2> threethree:print_count(5).
Number:1
Number:2
Number:3
Number:4
Number:5
ok
3> threethree:print_even_count(5).
Number:2
Number:4
ok

Cheers,
-Halzy

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.