Efficiently performing operations on Erlang Tuples - erlang

Say we wish to calculate the difference between two time-stamp:
66> T0=now().
{1387,611376,335905}
67> T1=now().
{1387,611383,156575}
68> T1-T0.
** exception error: an error occurred when evaluating an arithmetic expression
in operator -/2
called as {1387,611383,156575} - {1387,611376,335905}
69> {A1,A2,A3}=T0.
{1387,611376,335905}
70> {B1,B2,B3}=T1.
{1387,611383,156575}
71> Diff=(B1-A1)*1000000000000+(B2-A2)*1000000+(B3-A3).
6820670
72>
IS there a more efficient (elegant) way to do this than subtracting each corresponding element?
Thanks.

No, there is not more efficient way. See principally same way implemented timer:now_diff/2 in stdlib:
%%
%% Calculate the time difference (in microseconds) of two
%% erlang:now() timestamps, T2-T1.
%%
-spec now_diff(T2, T1) -> Tdiff when
T1 :: erlang:timestamp(),
T2 :: erlang:timestamp(),
Tdiff :: integer().
now_diff({A2, B2, C2}, {A1, B1, C1}) ->
((A2-A1)*1000000 + B2-B1)*1000000 + C2-C1.

If you only need comparison:
1> {1387,611383,156575} > {1387,611376,335905}.
true

Related

How to have a sum of numbers so that sum(4) would do 1+2+3+4

-module(test).
-export([sum/1]).
sum([]) -> 0;
sum([X|Xs]) -> X + sum(Xs)
This is what I have done so far though it only sums the numbers within a list like test:sum([1,2,3,4])
but I want it so that its like test:sum(4) will output 1+2...+n
How can I do this?
This function you have provided will sum values in list, but if you want to "overload" this function to also support integers then you can write:
-module(test).
-export([sum/1]).
sum([]) -> 0;
sum([X|Xs]) -> X + sum(Xs);
sum(0) -> 0;
sum(N) when is_integer(N) -> (N * (N + 1)) div 2.
This uses pattern matching to check type of the argument, and then pick proper "version" of the function to evaluate.
but I want it so that its like test:sum(4) will output 1+2...+n
Here's a recursive solution:
-module(my).
-compile(export_all).
sum(0) ->
0;
sum(X) ->
X + sum(X-1).
In the shell:
3> my:sum(1).
1
4> my:sum(2).
3
5> my:sum(3).
6
6> my:sum(4).
10
7> my:sum(5).
15
Note that if you call sum/1 with a negative number, sum/1 will recurse forever and eventually crash the shell, so you can add a guard to accept only positive numbers. Then if you call sum/1 with a negative number, you will get a function_clause error instead, which you get when: No matching function clause is found when evaluating a function call. Of course, you can also define another function clause that will handle negative numbers.
using tail recursion
here is the code below:
% function entry
sum(N) -> sum(N,0);
sum(0,Acc) -> Acc;
sum(N,Acc) -> sum(N-1,Acc+N).
Simple one line example with using Erlang functions:
sum(N) -> lists:sum(lists:seq(1, N)).

Make pairs out of a list in erlang

I'm trying to do a process on items in a sorted set in erlang, I call ZRANGE KEY 0 -1 WITHSCORES with eredis, the problem is it returns something like [<<"item1">>, <<"100">>, <<"item2">>, <<"200">>]. How can I run a function f on these items efficiently so that these calls occur: f(<<"item1">>, <<"100">>), f(<<"item2">>, <<"200">>)?
I solved it with something like this
f([X,Y|T]) -> [do_the_job(X,Y)|f(T)];
f([]) -> [].
then calling:
f(List).
Is there a more efficient way for doing so?
An optimized way is using tail-recursion. You can pass your list into do/1 function and it generates an empty list for storing the result of applying f/2 function on each two head items of the given list and then return the results:
do(List) ->
do(List, []).
do([X,Y | Tail], Acc) ->
do(Tail, [f(X, Y) | Acc]);
do([], Acc) ->
lists:reverse(Acc).
f(X, Y) ->
{X, Y}.
A note from Erlang documentation about tail-recursive efficiency:
In most cases, a recursive function uses more words on the stack for each recursion than the number of words a tail-recursive would allocate on the heap. As more memory is used, the garbage collector is invoked more frequently, and it has more work traversing the stack.

Counting down from N to 1

I'm trying to create a list and print it out, counting down from N to 1. This is my attempt:
%% Create a list counting down from N to 1 %%
-module(list).
-export([create_list/1]).
create_list(N) when length(N)<hd(N) ->
lists:append([N],lists:last([N])-1),
create_list(lists:last([N])-1);
create_list(N) ->
N.
This works when N is 1, but otherwise I get this error:
172> list:create_list([2]).
** exception error: an error occurred when evaluating an arithmetic expression
in function list:create_list/1 (list.erl, line 6)
Any help would be appreciated.
You should generally avoid using append or ++, which is the same thing, when building lists. They both add elements to the end of a list which entails making a copy of the list every time. Sometimes it is practical but it is always faster to work at the front of the list.
It is a bit unclear in which order you wanted the list so here are two alternatives:
create_up(N) when N>=1 -> create_up(1, N). %Create the list
create_up(N, N) -> [N];
create_up(I, N) ->
[I|create_up(I+1, N)].
create_down(N) when N>1 -> %Add guard test for safety
[N|create_down(N-1)];
create_down(1) -> [1].
Neither of these are tail-recursive. While tail-recursion is nice it doesn't always give as much as you would think, especially when you need to call a reverse to get the list in the right order. See Erlang myths for more information.
The error is lists:last([N])-1. Since N is an array as your input, lists:last([N]) will return N itself. Not a number you expect. And if you see the warning when compiling your code, there is another bug: lists:append will not append the element into N itself, but in the return value. In functional programming, the value of a variable cannot be changed.
Here's my implementation:
create_list(N) ->
create_list_iter(N, []).
create_list_iter(N, Acc) ->
case N > 0 of
true -> NewAcc = lists:append(Acc, [N]),
create_list_iter(N-1, NewAcc);
false -> Acc
end.
If I correctly understand your question, here is what you'll need
create_list(N) when N > 0 ->
create_list(N, []).
create_list(1, Acc) ->
lists:reverse([1 | Acc]);
create_list(N, Acc) ->
create_list(N - 1, [N | Acc]).
If you work with lists, I'd suggest you to use tail recursion and lists construction syntax.
Also, to simplify your code - try to use pattern matching in function declarations, instead of case expressions
P.S.
The other, perhaps, most simple solution is:
create_list(N) when N > 0 ->
lists:reverse(lists:seq(1,N)).

What is the name of |> in F# and what does it do?

A real F# noob question, but what is |> called and what does it do?
It's called the forward pipe operator. It pipes the result of one function to another.
The Forward pipe operator is simply defined as:
let (|>) x f = f x
And has a type signature:
'a -> ('a -> 'b) -> 'b
Which resolves to: given a generic type 'a, and a function which takes an 'a and returns a 'b, then return the application of the function on the input.
You can read more detail about how it works in an article here.
I usually refer to |> as the pipelining operator, but I'm not sure whether the official name is pipe operator or pipelining operator (though it probably doesn't really matter as the names are similar enough to avoid confusion :-)).
#LBushkin already gave a great answer, so I'll just add a couple of observations that may be also interesting. Obviously, the pipelining operator got it's name because it can be used for creating a pipeline that processes some data in several steps. The typical use is when working with lists:
[0 .. 10]
|> List.filter (fun n -> n % 3 = 0) // Get numbers divisible by three
|> List.map (fun n -> n * n) // Calculate squared of such numbers
This gives the result [0; 9; 36; 81]. Also, the operator is left-associative which means that the expression input |> f |> g is interpreted as (input |> f) |> g, which makes it possible to sequence multiple operations using |>.
Finally, I find it quite interesting that pipelining operaor in many cases corresponds to method chaining from object-oriented langauges. For example, the previous list processing example would look like this in C#:
Enumerable.Range(0, 10)
.Where(n => n % 3 == 0) // Get numbers divisible by three
.Select(n => n * n) // Calculate squared of such numbers
This may give you some idea about when the operator can be used if you're comming fromt the object-oriented background (although it is used in many other situations in F#).
As far as F# itself is concerned, the name is op_PipeRight (although no human would call it that). I pronounce it "pipe", like the unix shell pipe.
The spec is useful for figuring out these kinds of things. Section 4.1 has the operator names.
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html
Don't forget to check out the library reference docs:
http://msdn.microsoft.com/en-us/library/ee353754(v=VS.100).aspx
which list the operators.

Erlang: Why does this fail with a 'badarith' exception?

Is it possible to implement a closure in Erlang?
For example, how would I translate this snippet from Scheme?
(define (make-adder n)
(lamdba (x) (+ x n)))
I've tried the following, but I'm clearly missing something.
make_adder(n) ->
fun (x) -> x + n end.
Compiling this gives the error
Warning: this expression will fail with a 'badarith' exception
You can't add atoms. Variables start with Capital Letters in erlang. words starting with lower case letters are atoms.
In other words your problem is not related to funs at all, you just need to capitalize your variable names.
make_adder(N) ->
fun (X) -> X + N end.
Variables start with Capital Letters in erlang.
words starting with lower case letters are atoms.

Resources