Guard for tuple of integers - erlang

I have a function that accepts coordinates (tuple) as one of its arguments:
func({X, Y}, Something) when is_integer(X), is_integer(Y) -> ...
I want to ensure that the coordinates:
are tuple with 2 items (X and Y)
both X and Y are integers
I can use the guard as above, and it works all right. But, I have many functions that use the coordinates and I wanted to know if I can clean up somehow this construct (some macro?) so would have something like:
func(XY, Something) when ?is_coord(XY) -> ... % how to define ?is_coord
Is there a clean and idiomatic way to do that? Is it erlang-ish?
Edit
Erlang docs explicitly discourage defensive programming:
3.13 Do not program "defensively"
A defensive program is one where the programmer does not "trust" the
input data to the part of the system they are programming. In general
one should not test input data to functions for correctness. Most of
the code in the system should be written with the assumption that the
input data to the function in question is correct. Only a small part
of the code should actually perform any checking of the data. This is
usually done when data "enters" the system for the first time, once
data has been checked as it enters the system it should thereafter be
assumed correct.

There's a clean and I think pretty Erlang-ish way to define is_coord macro:
-define(is_coord(C), tuple_size(C) =:= 2
andalso is_integer(element(1, C))
andalso is_integer(element(2, C))).
func(Coord, Something) when ?is_coord(Coord) ->
...
Note that tuple_size/1 also implies is_tuple/1 check.

hmmm well you can't exactly define your own guards, since the idea is to be completely sure that they don't have side effects (http://www.erlang.org/doc/reference_manual/expressions.html#id80042).
This quick hack works:
-define(GUARD(Name, Args), Name({X, Y}, Args) when is_integer(X), is_integer(Y)).
-export([myfun/2]).
?GUARD(myfun, [A, B, C]) ->
io:format("hi~n"),
ok.
Although i don't personally like it... Probably you could do a parse transform if you really need it: http://chlorophil.blogspot.com.ar/2007/04/erlang-macro-processor-v1-part-i.html, or preprocess your sources with a template engine, like mustache: https://github.com/mojombo/mustache.erl
hope it helps!

Ning and marcelog's answers are both good and efficient, but personally i would either let the code as is or use one of them, and then :
1) define a type
-type point() :: {integer(),integer()}.
2) use Erlang's dialyzer

Another way is to use the parse transform library like guardian and write the code something like below.
-compile({parse_transform, guardian}).
func(XY, Something) when is_coord(XY) ->
do(Something);
func(XY, A) ->
filering_out.
is_coord({X, Y}) when is_integer(X), is_integer(Y)->
true;
is_coord(_) ->
false.
The func function is transformed to the similar function as written by Ning's case statement function.

You can use case:
-module(lab).
-compile(export_all).
go() ->
func({1, 2}, "1st try"),
func({a, 2}, "2nd try"),
func({1, 2, 3}, "3rd try").
func(XY, Something) ->
case is_coord(XY) of
true -> io:format("~p~n", [Something]);
false -> io:format("Not a coord~n")
end.
is_coord(XY) ->
case XY of
{X, Y} when is_integer(X), is_integer(Y) ->
true;
_ ->
false
end.
Test run:
> c(lab), lab:go().
"1st try"
Not a coord
Not a coord
ok

I just realized that we can have another solution.
We can define a coord record as:
-define(coord, {x = 0, y = 0}).
And then we can simply do:
func(XY, Something) when is_record(XY, coord) -> ...
We need to make sure we initialize x and y with integers when creating a coord record. (shouldn't be hard:))
... both X and Y are integers [checked]
and is_record(XY, coord) guarantees the structure of XY.
... are tuple with 2 items (X and Y) [checked]

I would say record checking (is_record) cannot provide any guaranty that both elements are integers.. So, if you need to be sure you have 2 elements tuple with integeres, I'd use
-define(is_coord(X), size(X)== 2 andalso is_integer(element(1,X)) andalso is_integer(element(2,X))).
rr(X) when ?is_coord(X) -> coord;
rr(_) -> not_coord.

Related

Performing Calculations on F# option types

I'm trying to write some function that handle errors by returning double options instead of doubles. Many of these functions call eachother, and so take double options as inputs to output other double options. The problem is, I can't do with double options what I can do with doubles--something simple like add them using '+'.
For example, a function that divides two doubles, and returns a double option with none for divide by zero error. Then another function calls the first function and adds another double option to it.
Please tell me if there is a way to do this, or if I have completely misunderstood the meaning of F# option types.
This is called lifting - you can write function to lift another function over two options:
let liftOpt f o1 o2 =
match (o1, o2) with
| (Some(v1), Some(v2)) -> Some(f v1 v2)
| _ -> None
then you can supply the function to apply e.g.:
let inline addOpt o1 o2 = liftOpt (+) o1 o2
liftA2 as mentioned above will provide a general way to 'lift' any function that works on the double arguments to a function that can work on the double option arguments.
However, in your case, you may have to write special functions yourself to handle the edge cases you mention
let (<+>) a b =
match (a, b) with
| (Some x, Some y) -> Some (x + y)
| (Some x, None) -> Some (x)
| (None, Some x) -> Some (x)
| (None, None) -> None
Note that liftA2 will not put the cases where you want to add None to Some(x) in automatically.
The liftA2 method for divide also needs some special handling, but its structure is generally what we would write ourselves
let (</>) a b =
match (a, b) with
| (Some x, Some y) when y <> 0.0d -> Some (x/y)
| _ -> None
You can use these functions like
Some(2.0) <+> Some(3.0) // will give Some(5.0)
Some(1.0) </> Some(0.0) // will give None
Also, strictly speaking, lift is defined as a "higher order function" - something that takes a function and returns another function.
So it would look something like this:
let liftOpt2 f =
(function a b ->
match (a, b) with
| (Some (a), Some (b)) -> f a b |> Some
| _ -> None)
In the end, I realized what I was really looking for was the Option.get function, which simply takes a 'a option and returns an 'a. That way, I can pattern match, and return the values I want.
In this case you might want to consider Nullables over Options, for two reasons:
Nullables are value types, while Options are reference types. If you have large collections of these doubles, using Nullables will keep the numbers on the stack instead of putting them on the heap, potentially improving your performance.
Microsoft provides a bunch of built-in Nullable Operators that do let you directly perform math on nullables, exactly as you're trying to do with options.

Why does Array2D not have a fold operation?

I just bumped into a case where it would be useful to have fold/foldi methods on an Array2D and I wondered, if there is a reason, why Array2D does not have them.
As my array2d is quite huge, I would not want to transform it first to some other format.
Is it simply a rare use case or are there technical reasons, why those methods were not added? Or is there a way to achieve the same without touching the data in the array (as in move it)?
I think having this function in the standard Array2D module would be quite useful. You can open an issue for the Visual F# repository and help us add it :-).
In addition to what #scrwtp wrote, you can also use more direct mutable implementation. For basic functions like this, I think using mutation is fine and it is going to be a bit faster:
let foldi (folder: int -> int -> 'S -> 'T -> 'S) (state: 'S) (array: 'T[,]) =
let mutable state = state
for x in 0 .. Array2D.length1 array - 1 do
for y in 0 .. Array2D.length2 array - 1 do
state <- folder x y state (array.[x, y])
state
I don't think there's any particular reason why Array2D doesn't come with those functions in standard, since it does have map/mapi. Probably the use cases where you want to process a multidimensional array are better served by using a jagged array anyway, so there's little incentive to add them.
There's no reason why you can't define them yourself.
Here's an example of a foldi:
let foldi (folder: int -> int -> 'S -> 'T -> 'S) (state: 'S) (array: 'T[,]) =
seq {
for x in 0 .. Array2D.length1 array - 1 do
for y in 0 .. Array2D.length2 array - 1 do
yield (x, y, array.[x, y])
}
|> Seq.fold (fun acc (x, y, e) -> folder x y acc e) state
For a regular fold and a more in-depth explanation how it works, you may look here.
I generally use Seq.cast if I need to use folding functions, but this works only for fold (not for foldi).
I am adding this solution, if one needs, for example, scan:
let array2dFold folder (state:'State) (source:'T[,]) =
source
|> ( Seq.cast<'T> >> Seq.fold folder state )
Since it does not rely on mutation it is highly likely that it is slower than previous solutions.

Basic Erlang - Alternatives to function calls in guards etc

I'm trying to learn Erlang, coming from a C++/Java background. This forces me to re-think all my methods.
Right now I'm trying to write something that returns the N first elements of a list. Right now it looks like this, although I can't call functions in guards or if expressions. What is the Erlang way of doing this?
take([Xh|Xr],N,Xn) ->
if
len(Xn) /= N -> take(Xr,N,app(Xh, Xn));
len(Xn) == N -> Xn
end.
I also tried calling the function before, but that didn't work either:
take([Xh|Xr],N,Xn) ->
G = len(Xn);
if
G /= N -> take(Xr,N,app(Xh, Xn));
G == N -> Xn
end.
Generally with this kind of problems, you need to switch to a recursive way of thinking instead of the iterative approach you're using. Here's what I would do:
take(List, N) ->
take(List, N, []).
take(_List, 0, Acc) ->
lists:reverse(Acc);
take([H|T], N, Acc) ->
take(T, N - 1, [H|Acc]).
It's really common for people coming from languages that promote the iterative approach to try and shoehorn that approach into Erlang. The problem is that Erlang doesn't have the primitives for doing it that way since it's a functional language. So you're forced to do it the functional way, and in the end it's often the more elegant approach.
In addition to Fylke's solution, there is also something to be said for a body recursive approach:
take(_List,0) ->
[];
take([H|T],N) ->
[H|take(T,N-1)].
Your approach isn't wrong per se, it just needs a bit of help:
-module(foo).
-compile(export_all).
take([Xh|Xr],N,Xn) ->
G = length(Xn), %% This line had trouble. Use length/1 and end with , not ;
if
G /= N ->
take(Xr,N,app(Xh, Xn));
G == N ->
Xn
end.
app(X, L) ->
L ++ [X].
As other people hints, your approach is not very Erlang idiomatic, and the other solutions are far better. Also, look up the source code for lists:split/2
https://github.com/erlang/otp/blob/master/lib/stdlib/src/lists.erl#L1351

Dynamic pattern matching

How can I do dynamic pattern matching in Erlang?
Supose I have the function filter/2 :
filter(Pattern, Array)
where Pattern is a string with the pattern I want to match (e.g "{book, _ }" or "{ebook, _ }") typed by an user and Array is an array of heterogenous elements (e.g {dvd, "The Godfather" } , {book, "The Hitchhiker's Guide to the Galaxy" }, {dvd, "The Lord of Rings"}, etc) Then I would like filter/2 above to return the array of elements in Array that match Pattern.
I've tried some ideas with erl_eval without any sucess...
tks in advance.
With little bit documentation study:
Eval = fun(S) -> {ok, T, _} = erl_scan:string(S), {ok,[A]} = erl_parse:parse_exprs(T), {value, V, _} = erl_eval:expr(A,[]), V end,
FilterGen = fun(X) -> Eval(lists:flatten(["fun(",X,")->true;(_)->false end."])) end,
filter(FilterGen("{book, _}"), [{dvd, "The Godfather" } , {book, "The Hitchhiker's Guide to the Galaxy" }, {dvd, "The Lord of Rings"}]).
[{book,"The Hitchhiker's Guide to the Galaxy"}]
Is there any special reason why you want the pattern in a string?
Patterns as such don't exist in Erlang, they can really only occur in code. An alternative is to use the same conventions as with ETS match and select and write your own match function. It is really quite simple. The ETS convention uses a term to represent a pattern where the atoms '$1', '$2', etc are used as variables which can be bound and tested, and '_' is the don't care variable. So your example patterns would become:
{book,'_'}
{ebook,'_'}
{dvd,"The Godfather"}
This is probably the most efficient way of doing it. There is the possibility of using match specifications here but it would complicate the code. It depends on how complicated matching you need.
EDIT:
I add without comment code for part of the matcher:
%% match(Pattern, Value) -> {yes,Bindings} | no.
match(Pat, Val) ->
match(Pat, Val, orddict:new()).
match([H|T], [V|Vs], Bs0) ->
case match(H, V, Bs0) of
{yes,Bs1} -> match(T, Vs, Bs1);
no -> no
end;
match('_', _, Bs) -> {yes,Bs}; %Don't care variable
match(P, V, Bs) when is_atom(P) ->
case is_variable(P) of
true -> match_var(P, V, Bs); %Variable atom like '$1'
false ->
%% P just an atom.
if P =:= V -> {yes,Bs};
true -> no
end
end.
match_var(P, V, Bs) ->
case orddict:find(P, Bs) of
{ok,B} when B =:= V -> {yes,Bs};
{ok,_} -> no;
error -> {yes,orddict:store(P, V, Bs)}
end.
You can use lists:filter/2 to do the filtering part. Converting the string to code is a different matter. Are all the patterns in the form of {atom, _}? If so, you might be able to store the atom and pass that into the closure argument of lists:filter.
Several possibilities come to the mind, depending on how dynamic the patterns are and what features you need in your patterns:
If you need exactly the syntax of erlang patterns and the pattern doesnt't change very often. You could create the matching source code and write it to a file. Use compile:file to create a binary and load this with code:load_binary.
Advantage: Very fast matching
Disadvantage: overhead when pattern changes
Stuff the data from Array into ETS and use match specifications to get out the data
You might use fun2ms to help create the match specification. But fun2ms normally is used as a parse transfor during compile time. There is also a mode used by the shell that can be made to work from strings with the help of the parser probably. For details see ms_transform
There might also be some way to use qlc but I didn't look into this in detail.
In any case be careful to sanitize your matching data if it comes from untrusted sources!

right rotate a List in Erlang

I am getting myself familiar to Sequential Erlang (and the functional programming thinking) now. So I want to implement the following two functionality without the help of BIF. One is left_rotate (which I have come up with the solution) and the other is right_rotate (which I am asking here)
-export(leftrotate/1, rightrotate/1).
%%(1) left rotate a lits
leftrotate(List, 0) ->
List;
leftrotate([Head | Tail], Times) ->
List = append(Tail, Head),
leftrotate(List, Times -1).
append([], Elem)->
[Elem];
append([H|T], Elem) ->
[H | append(T, Elem)].
%%right rotate a list, how?
%%
I don't want to use BIF in this exercise. How can I achieve the right rotation?
A related question and slightly more important question. How can I know one of my implementation is efficient or not (i.e., avoid unnecessary recursion if I implement the same thing with the help of a BIF, and etc.)
I think BIF is built to provide some functions to improve efficiency that functional programming is not good at (or if we do them in a 'functional way', the performance is not optimal).
The efficiency problem you mention has nothing to do with excessive recursion (function calls are cheap), and everything to do with walking and rebuilding the list. Every time you add something to the end of a list you have to walk and copy the entire list, as is obvious from your implementation of append. So, to rotate a list N steps requires us to copy the entire list out N times. We can use lists:split (as seen in one of the other answers) to do the entire rotate in one step, but what if we don't know in advance how many steps we need to rotate?
A list really isn't the ideal data structure for this task. Lets say that instead we use a pair of lists, one for the head and one for the tail, then we can rotate easily by moving elements from one list to the other.
So, carefully avoiding calling anything from the standard library, we have:
rotate_right(List, N) ->
to_list(n_times(N, fun rotate_right/1, from_list(List))).
rotate_left(List, N) ->
to_list(n_times(N, fun rotate_left/1, from_list(List))).
from_list(Lst) ->
{Lst, []}.
to_list({Left, Right}) ->
Left ++ reverse(Right).
n_times(0, _, X) -> X;
n_times(N, F, X) -> n_times(N - 1, F, F(X)).
rotate_right({[], []}) ->
{[], []};
rotate_right({[H|T], Right}) ->
{T, [H|Right]};
rotate_right({[], Right}) ->
rotate_right({reverse(Right), []}).
rotate_left({[], []}) ->
{[], []};
rotate_left({Left, [H|T]}) ->
{[H|Left], T};
rotate_left({Left, []}) ->
rotate_left({[], reverse(Left)}).
reverse(Lst) ->
reverse(Lst, []).
reverse([], Acc) ->
Acc;
reverse([H|T], Acc) ->
reverse(T, [H|Acc]).
The module queue provides a data structure something like this. I've written this without reference to that though, so theirs is probably more clever.
First, your implementation is a bit buggy (try it with the empty list...)
Second, I would suggest you something like:
-module(foo).
-export([left/2, right/2]).
left(List, Times) ->
left(List, Times, []).
left([], Times, Acc) when Times > 0 ->
left(reverse(Acc), Times, []);
left(List, 0, Acc) ->
List ++ reverse(Acc);
left([H|T], Times, Acc) ->
left(T, Times-1, [H|Acc]).
right(List, Times) ->
reverse(foo:left(reverse(List), Times)).
reverse(List) ->
reverse(List, []).
reverse([], Acc) ->
Acc;
reverse([H|T], Acc) ->
reverse(T, [H|Acc]).
Third, for benchmarking your functions, you can do something like:
test(Params) ->
{Time1, _} = timer:tc(?MODULE, function1, Params),
{Time2, _} = timer:tc(?MODULE, function2, Params),
{{solution1, Time1}, {solution2, Time2}}.
I didn't test the code, so look at it critically, just get the idea.
Moreover, you might want to implement your own "reverse" function. It will be trivial by using tail recursion. Why not to try?
If you're trying to think in functional terms then perhaps consider implementing right rotate in terms of your left rotate:
rightrotate( List, 0 ) ->
List;
rightrotate( List, Times ) ->
lists:reverse( leftrotate( lists:reverse( List ), Times ) ).
Not saying this is the best idea or anything :)
Your implementation will not be efficient since the list is not the correct representation to use if you need to change item order, as in a rotation. (Imagine a round-robin scheduler with many thousands of jobs, taking the front job and placing it at the end when done.)
So we're actually just asking ourself what would be the way with least overhead to do this on lists anyway. But then what qualifies as overhead that we want to get rid of? One can often save a bit of computation by consing (allocating) more objects, or the other way around. One can also often have a larger than needed live-set during the computation and save allocation that way.
first_last([First|Tail]) ->
put_last(First, Tail).
put_last(Item, []) ->
[Item];
put_last(Item, [H|Tl]) ->
[H|put_last(Item,Tl)].
Ignoring corner cases with empty lists and such; The above code would cons the final resulting list directly. Very little garbage allocated. The final list is built as the stack unwinds. The cost is that we need more memory for the entire input list and the list in construction during this operation, but it is a short transient thing. My damage from Java and Lisp makes me reach for optimizing down excess consing, but in Erlang you dont risk that global full GC that kills every dream of real time properties. Anyway, I like the above approach generally.
last_first(List) ->
last_first(List, []).
last_first([Last], Rev) ->
[Last|lists:reverse(Rev)];
last_first([H|Tl], Rev) ->
last_first(Tl, [H|Rev]).
This approach uses a temporary list called Rev that is disposed of after we have passed it to lists:reverse/1 (it calls the BIF lists:reverse/2, but it is not doing anything interesting). By creating this temporary reversed list, we avoid having to traverse the list two times. Once for building a list containing everything but the last item, and one more time to get the last item.
One quick comment to your code. I would change the name of the function you call append. In a functional context append usually means adding a new list to the end of a list, not just one element. No sense in adding confusion.
As mentioned lists:split is not a BIF, it is a library function written in erlang. What a BIF really is is not properly defined.
The split or split like solutions look quite nice. As someone has already pointed out a list is not really the best data structure for this type of operation. Depends of course on what you are using it for.
Left:
lrl([], _N) ->
[];
lrl(List, N) ->
lrl2(List, List, [], 0, N).
% no more rotation needed, return head + rotated list reversed
lrl2(_List, Head, Tail, _Len, 0) ->
Head ++ lists:reverse(Tail);
% list is apparenly shorter than N, start again with N rem Len
lrl2(List, [], _Tail, Len, N) ->
lrl2(List, List, [], 0, N rem Len);
% rotate one
lrl2(List, [H|Head], Tail, Len, N) ->
lrl2(List, Head, [H|Tail], Len+1, N-1).
Right:
lrr([], _N) ->
[];
lrr(List, N) ->
L = erlang:length(List),
R = N rem L, % check if rotation is more than length
{H, T} = lists:split(L - R, List), % cut off the tail of the list
T ++ H. % swap tail and head

Resources