Help!
Vladimir Sekissov
svg@REDACTED
Wed Aug 13 22:43:21 CEST 2003
Good day,
f(X) ->
...
{_, Chapters} = element(4, Book),
case lists:keysearch(X, 2, Chapters) of
{value, {_, _, Header}} ->
{ok, Header};
Other ->
Other
end.
But may be it would be better to use records here if book format is
fixed:
-record(book, {preface, contents, chapters}).
-record(chapter, {num, header}).
get_chapter(N, B=#book{chapters=Cs}) ->
case lists:dropwhile(fun (C=#chapter{num=N}) -> false;
(_) -> true
end, Cs) of
[C=#chapter{header=H}|_] ->
{ok, Header};
[] ->
undefined
end.
Or xml-like {book, [{AttrName, AttrValue}], [Content]} if it is
float. You can effectively traverse it with simple generic functions
in such case. For example:
%%
fold_tree(Node={Name, Args}, DownHlr, HereHlr, UpHlr, Seed) ->
fold_tree(Node={Name, Args, []}, DownHlr, HereHlr, UpHlr, Seed);
fold_tree(Node={Name, Args, Content}, DownHlr, HereHlr, UpHlr, Seed) ->
NodeEl = {Name, Args},
ChildSeed =
fold_content(Content,
DownHlr, HereHlr, UpHlr, DownHlr(NodeEl, Seed)),
UpHlr(NodeEl, Seed, ChildSeed);
fold_tree(Nodes=[N|_], DownHlr, HereHlr, UpHlr, Seed) when is_tuple(N) ->
fold_content(Nodes, DownHlr, HereHlr, UpHlr, Seed);
fold_tree(Str, DownHlr, HereHlr, UpHlr, Seed) when is_list(Str) ->
HereHlr(Str, Seed).
fold_content(Nodes, DownHlr, HereHlr, UpHlr, Seed) ->
lists:foldl(fun (N, S) ->
fold_tree(N, DownHlr, HereHlr, UpHlr, S)
end, Seed, normalize_el_content(Nodes)).
normalize_el_content(C=[I|_]) when is_integer(I) ->
%% string() -> [string()]
[C];
normalize_el_content(C) ->
C.
Best Regards,
Vladimir Sekissov
jilani.khaldi> I am trying in vain to write a function that once I inserted the number of
jilani.khaldi> a chapter of a book it gives me as result its title.
jilani.khaldi> For example: f(2) -> Chapitre 2
jilani.khaldi>
jilani.khaldi> I tried many ways but can reach the correct result.
jilani.khaldi>
jilani.khaldi> -module(chapter).
jilani.khaldi> -export([f/1]).
jilani.khaldi> f(X) ->
jilani.khaldi> {_,_,_,Y} = {book, preface, contents,{chapters,[{chapter, 1, 'Chapitre 1'},
jilani.khaldi> {chapter, 2, 'Chapitre 2'}, {chapter, 3, 'Chapitre 3'}]}},
jilani.khaldi> {Z,Chapters} = Y...
jilani.khaldi> Y now has the list of chapters, but... Surely there are many ways to get
jilani.khaldi> the result, but I couldn't find any even if it seems so simple.
jilani.khaldi>
jilani.khaldi> Thanks!
jilani.khaldi>
jilani.khaldi> jilani
More information about the erlang-questions
mailing list