public
Description: Haskell's Data.List functions for Erlang. That was the idea anyway. Good ideas from other languages will be shamelessly stolen too.
Homepage: http://12monkeys.co.uk
Clone URL: git://github.com/hassy/hslists.git
Added transpose/1 and product/1.
hassy (author)
Tue Mar 25 06:59:08 -0700 2008
commit  a06f1dec51547c3c40469cd408ac5aa403e2ef2e
tree    76b0edb4b56bd5ea1b5213fd8f9aff557ace3ffa
parent  87e308df969437761db30f2d462f5bf0429a3994
...
1
2
 
3
4
5
6
 
7
8
9
10
11
 
 
 
12
 
13
14
15
16
 
17
18
19
20
21
 
22
23
24
...
30
31
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
1
 
2
3
4
5
 
6
7
8
9
10
 
11
12
13
14
15
16
17
 
 
18
19
20
21
22
 
23
24
25
26
...
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
0
@@ -1,24 +1,26 @@
0
 %%% @doc Additional list functions, inspired by Haskell's Data.List.
0
-%%% @author Hasan Veldstra <hasan@12monkeys.co.uk>
0
+%%% @author Hasan Veldstra <hasan@12monkeys.co.uk> [http://12monkeys.co.uk]
0
 %%% Distributed under the same license as Erlang.
0
 
0
 -module(hslists).
0
--import(lists, [all/2, append/1, foreach/2, reverse/1]).
0
+-import(lists, [all/2, append/1, duplicate/2, foldl/3, foreach/2, map/2, reverse/1, seq/2]).
0
 
0
 %% Basic functions.
0
 -export([init/1]).
0
 %% List transformations.
0
--export([intersperse/2, intercalate/2]).
0
+-export([intersperse/2, intercalate/2, transpose/1]).
0
+%% Folds.
0
+-export([product/1]).
0
 
0
+-compile(export_all).
0
 
0
 %% @doc Returns all the elements of a list except the last one.
0
-%% The list must be finite and non-empty.
0
-init(L) when is_list(L) andalso L =/= [] ->
0
+init(L) when is_list(L) ->
0
     reverse(tl(reverse(L))).
0
 
0
 %% @doc Takes an element and a list and 'intersperses' that element between
0
 %% the elements of the list.
0
-intersperse(Elt, L) when is_list(L) ->
0
+intersperse(Elt, L) when is_list(L) andalso L =/= [] ->
0
     tl(intersperse1(Elt, L, [])).
0
 
0
 intersperse1(Elt, [Hd | Tl], Acc) ->
0
@@ -30,3 +32,32 @@ intersperse1(_Elt, [], Acc) ->
0
 %% result.
0
 intercalate(Xs, Xss) ->
0
     append(intersperse(Xs, Xss)).
0
+
0
+%% @doc Transposes the rows and columns of its argument. For example:<br />
0
+%% <code>transpose([[1, 2, 3], [a, b, c]]) = [[1, a], [2, b], [3, c]]</code> <br />
0
+%% All sub-lists must be of the same length.
0
+transpose(L = [Row | _Restrows]) ->
0
+ Len = length(Row),
0
+ lists:foreach(fun(X) ->
0
+ Len = length(X)
0
+ end,
0
+ L),
0
+ Acc = duplicate(Len, []),
0
+ transpose1(L, Acc).
0
+
0
+transpose1([Row | Restrows], Acc) ->
0
+ Newacc = lists:zipwith(fun(X, Y) ->
0
+ Y ++ [X]
0
+ end,
0
+ Row, Acc),
0
+ transpose1(Restrows, Newacc);
0
+transpose1([], Acc) ->
0
+ Acc.
0
+
0
+%% @doc Computes the product of a list of numbers.
0
+product([Hd | Tl]) ->
0
+ foldl(fun(X, Acc) ->
0
+ X * Acc
0
+ end,
0
+ Hd,
0
+ Tl).

Comments

    No one has commented yet.