[erlang-questions] why does the guard not working

Richard A. O'Keefe ok@REDACTED
Mon Feb 16 00:21:08 CET 2015


I wrote:
>> Of course, if you know how to iterate over the elements of a list,
>> you could start by making a list of the numbers you want, and
>> then iterate over that.  For example, you could write
>> 
>> print_even_integers(N) when is_integer(N), N >= 0 ->
>>     lists:foreach(
>>         fun (X) -> io:format("Number: ~p~n", [X]) end,
>>         lists:seq(2, N, 2)).
>> 
>> because (recursive) functions "generate an additive sequence of
>> integers" and "do this to every element of that list" have already
>> been written.  It has been argued that functional programming is
>> not so much about functions as about writing program pieces you
>> can just plug together.

On 13/02/2015, at 8:01 pm, Roelof Wobben <r.wobben@REDACTED> wrote:
> The problem is here you use the lists functions and I think Im now allowed to use them.

There's a little misunderstanding here.
I was not saying "here is a better way to solve this exercise AS an exercise".
I was providing a lesson: "the way you solve the exercise AS an exercise
is NOT the way you would solve it if you had it as a REAL WORLD problem."

In Haskell, I might write

n = ...
main = putStr $ unlines $ map show $ [2,4..n]
-- [2,4..n] make the list of even integers
-- map show $ .. convert every element to a string
-- unlines $ paste the strings together with a newline at the end of each
-- putStr $ .. print the string

where I would have written no loop or recursive function myself.
Yes, to use functional programming languages effectively you do have to
master recursion (which is really no harder than iteration).
But eventually, you should be writing fewer and fewer such functions
while *using* more and more.

Now that more and more programming languages (Python, Java, C#,
Javascript, ..., even C has anonymous functions in Mac OS X) are
catching up with where functional programming was in the 1960s, this
kind of abstraction is becoming possible quite generally, so this
way of thinking is becoming useful even in quite surprising languages.




More information about the erlang-questions mailing list