jungerl /lib/ce/src/ce_lib.erl

Language Erlang Lines 220
MD5 Hash b9bf2d3396b7ecfc05711cbeee344c86 Estimated Cost $2,433 (why?)
Repository https://github.com/gebi/jungerl.git View Raw File View Project SPDX
  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
 27
 28
 29
 30
 31
 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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
%%% BEGIN ce_lib.erl %%%
%%%
%%% ce - Miscellaneous Programming Support Libraries for Erlang/OTP
%%% Copyright (c)2003 Cat's Eye Technologies.  All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions
%%% are met:
%%%
%%%   Redistributions of source code must retain the above copyright
%%%   notice, this list of conditions and the following disclaimer.
%%%
%%%   Redistributions in binary form must reproduce the above copyright
%%%   notice, this list of conditions and the following disclaimer in
%%%   the documentation and/or other materials provided with the
%%%   distribution.
%%%
%%%   Neither the name of Cat's Eye Technologies nor the names of its
%%%   contributors may be used to endorse or promote products derived
%%%   from this software without specific prior written permission.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
%%% CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
%%% INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
%%% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
%%% DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
%%% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
%%% OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
%%% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
%%% OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
%%% ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
%%% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
%%% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%%% POSSIBILITY OF SUCH DAMAGE. 

%% @doc Miscellaneous spiffy stuff library.
%%
%% @end

-module(ce_lib).
-vsn('JUNGERL').
-author('catseye@catseye.mb.ca').
-copyright('Copyright (c)2003 Cat`s Eye Technologies. All rights reserved.').

-export([iterate/4, repeat/2]).
-export([breed/1]).
-export([eval/1]).
-export([call_stack/0]).
-export([clean/2, place/2]).
-export([attempt/2, attempt/3]).
-export([compose/1]).
-export([to_integer/2, to_float/2, to_string/1, to_string/2]).

%% @spec iterate(integer(), integer(), fun(), term()) -> term()
%% @doc Implements iteration with a counter variable.
%% Not dissimilar to 'for loops' in other languages.

iterate(I, Q, Fun, Acc) when Q < I -> Acc;
iterate(I, N, Fun, Acc) ->
  Acc0 = Fun(I, Acc),
  iterate(I+1, N, Fun, Acc0).

%% @spec repeat(integer(), fun()) -> [term()]
%% @doc Implements opaque finite repetition.
%% Not dissimilar to the 'repeat' loop in LOGO.
%% This version is tail-recursive and returns a list of all
%% evaluated results.

repeat(N, F) when integer(N) -> lists:reverse(repeat(N, F, [])).

repeat(0, F, A) -> A;
repeat(N, F, A) -> repeat(N - 1, F, [F() | A]).

%% @spec breed(term()) -> term()
%% @doc Returns a copy of a deep aggregate of data
%% with each Fun/0 object contained within replaced by
%% the result of running it.

breed([H|T]) -> [breed(H) | breed(T)];
breed(F) when function(F) -> apply(F, []);
breed(T) when tuple(T) -> breed_tuple(T, size(T));
breed(Q) -> Q.

breed_tuple(T, 0) -> {};
breed_tuple(T, N) ->
  erlang:append_element(breed_tuple(T, N-1), breed(element(N, T))).

%% @spec eval(string()) -> term()
%% @doc Evaluates a string as an Erlang expression.
%% This adds reflectivity to Erlang with a simple, Perl-like
%% interface.

eval(S) -> eval(S, []).
eval(S, PT) when list(S) ->
  {ok, T, _} = erl_scan:string(S),
  {ok, C} = erl_parse:parse_exprs(T),
  % execute all parse transforms in PT
  {value, Y, _} = erl_eval:exprs(C, erl_eval:bindings(erl_eval:new_bindings())),
  Y.

%% @spec call_stack() -> [{Module, Function, Arity}]
%% @doc Returns the current Erlang call stack (not including
%% <code>ce_lib:call_stack/0</code>).

call_stack() ->
  {'EXIT', {Error, CallStack}} = (catch 1 = 2),
  tl(CallStack).

%% @spec place(term(), term()) -> ok
%% @doc Places the given value in the process dictionary iff the given key
%% does not yet exist.  Exclusive use of place/2 instead of erlang:put/2
%% imposes the restriction of single-assignment on the process dictionary.

place(Key, Value) ->
  case erlang:get(Key, Value) of
    undefined ->
      put(Key, Value),
      ok;
    _ ->
      throw({error, already_set})
  end.

%% @spec clean(fun(), [{key(), value()}]) -> term()
%% @doc Evaluate a given Fun with a new, temporary process dictionary.
%% The new process dictionary will contain only the values given to clean/2,
%% and will be reset to the old process dictionary after the Fun has been
%% evaluated.  Simulates local variables with dynamic scope as found in 
%% many non-single-assignment languages.

clean(F, L) ->
  ProcessDictionary = erase(),
  lists:foreach(fun({K,V}) -> put(K,V) end, L),
  Result = F(),
  erase(),
  lists:foreach(fun({K,V}) -> put(K,V) end, ProcessDictionary),
  Result.

%% @spec attempt(function(), [term()]) -> {ok, term()} | {error, term()}
%% @doc Catches errors from an error-throwing function.
%% Thanks to Thomas Arts for this code.

attempt(F, Args) ->
  case catch apply(F, Args) of
    {'EXIT', Why} -> {error, Why};
            Other -> {ok, Other}
  end.

%% @spec attempt(function(), [term()], term()) -> term()
%% @doc Catches errors and returns a default value if error thrown.
%% Also can be used with functions which return {ok, Result} | {error, Why}.

attempt(F, Args, Default) ->
  case catch apply(F, Args) of
    {'EXIT', _} -> Default;
     {error, _} -> Default;
    {ok, Value} -> Value;
          Other -> Other
  end.

%% @spec compose([function()]) -> function()
%% @doc Composes a function by chaining the results of a list of functions.
%% Thanks to Alex Peake for this code.

compose([Fn]) -> Fn;
compose([Fn | FnTail]) ->
  fun(Args) ->
    apply(Fn, [apply(compose(FnTail), [Args])])
  end.

%% @spec to_integer(term(), integer()) -> integer()
%% @doc Tries to convert any term into an integer, using default value if it
%% cannot be done.

to_integer(F, D) when is_float(F) ->
  trunc(F + 0.5);
to_integer(I, D) when is_integer(I) ->
  I;
to_integer(S, D) when is_list(S) ->
  case catch list_to_integer(S) of
    F when integer(F) -> F;
    {'EXIT', Reason} -> D
  end;
to_integer(X, D) -> D.

%% @spec to_float(term(), float()) -> float()
%% @doc Tries to convert any term into a float, using default value if it
%% cannot be done.

to_float(F, D) when is_float(F) ->
  F;
to_float(I, D) when is_integer(I) ->
  I * 1.0;
to_float(S, D) when is_list(S) ->
  case catch list_to_float(S) of
    F when number(F) -> F;
    {'EXIT', Reason} ->
      case catch list_to_integer(S) of
        G when integer(G) -> G * 1.0;
	{'EXIT', Reason0} -> D
      end
  end;
to_float(X, D) -> D.

to_string(X) -> to_string(X, "").

%% @spec to_string(term(), string()) -> string()
%% @doc Tries to convert any term into a string, using default value if it
%% cannot be done.

to_string(F, D) when is_float(F) ->
  float_to_list(F);
to_string(I, D) when is_integer(I) ->
  integer_to_list(I);
to_string(A, D) when is_atom(A) ->
  atom_to_list(A);
to_string(S, D) when is_list(S) -> S;
to_string(X, D) -> io_lib:format("~w", [X]).

%%% END of ce_lib.erl %%%
Back to Top