Chapter 3 flatten exercise -- can be identify a list via pattern matching?

37 views
Skip to first unread message

Hugo Estrada

unread,
Dec 23, 2009, 3:51:46 PM12/23/09
to Erlang Programming
Hi there,

i am working on the exercise on chapter 3 and I am to the one where
one is supposed to flatten a list with nested elements.

It seems to me that I must identify if the head element that I am
handling at that moment is a list or not. I know that there is a
predicate, is_list/1, that will do this for me.

Am I suppose to use the predicate, or is there a pattern matching that
can tease out if the current H is a list or not?

Thanks for the good exercises, by the way. It actually makes one
really learn the language.

Thanks in advance for future answers,

Hugo

Andrey

unread,
Dec 25, 2009, 4:28:38 PM12/25/09
to Erlang Programming
It is possible to solve this exercise using only recursion and pattern
matching. You just need to define correct order of patterns.

Andrey

Hugo Estrada

unread,
Dec 25, 2009, 7:13:09 PM12/25/09
to erlang-prog...@googlegroups.com
Thanks! I will try to solve it with pattern matching then :)


--
Erlang Programming Website:
http://www.erlangprogramming.org/

Sami

unread,
Jan 4, 2010, 5:51:58 PM1/4/10
to Erlang Programming
You can test against the pattern [H|N]:
flatten([[H|T1]|T2]) -> concatenate([flatten([H|T1]), flatten(T2)]).

Sami

Reply all
Reply to author
Forward
0 new messages