Basic example of Map in Erlang - erlang

Day 2 of learning Erlang. I am trying to learn the basics of using Map in Erlang by creating a simple map function that takes in any predicate and list (passed in by the user) and checks if the the predicate returns true or false and stores the result in the list.
So if the user passes in (> 3) as the predicate and the list contains [3,4,5] the desired output would be [false, true, true].
This is what I tried:
applyMap (P, LST) -> lists:map(P LST).
I appreciate any suggestions on how to do this.
Many thanks in advance!

I think you're just missing a , between P and LST in your call to lists:map. Try this one:
applyMap (P, LST) -> lists:map(P, LST).
If you pass in the anonymous function fun(X) -> X > 3 end to your applyMap, you should get your desired output.
Example:
applyMap (fun(X) -> X > 3 end, LST).

There are two problems: first, you're missing the comma between P and LST, but second, you can't use Haskell-style curried functions like (> 3). lists:map((> 3), [1,2,3]) isn't correct in Erlang.
In Haskell, (> 3) is the curried form of \n -> n > 3. In Erlang, you have to write it explicitly:
lists:map(fun(N) -> N > 3 end, [2,4,6])

Related

Is there a name for this higher order function?

I very frequently want to apply the same argument twice to a binary function f, is there a name for this convert function/combinator?
// convert: f: ('a -> 'a -> 'b) -> 'a -> 'b
let convert f x = f x x
Example usage might be partially applying convert with the multiplication operator * to fix the multiplicand and multiplier:
let fixedMultiplication = convert (*)
fixedMultiplication 2 // returns 4
That combinator is usually called a warbler; the name comes from Raymond Smullyan's book To Mock a Mockingbird, which has a bunch of logic puzzles around combinator functions, presented in the form of birds that can imitate each other's songs. See this usage in Suave, and this page which lists a whole bunch of combinator functions (the "standard" ones and some less-well-known ones as well), and the names that Smullyan gave them in his book.
Not really an answer to what it's called in F#, but in APL or J, it's called the "reflexive" (or perhaps "reflex") operator. In APL it is spelt ⍨ and used monadically – i.e. applied to one function (on its left). In J it's called ~, and used in the same way.
For example: f⍨ x is equivalent to x f x (in APL, functions that take two arguments are always used in a binary infix fashion).
So the "fixedMultiplication" (or square) function is ×⍨ in APL, or *~ in J.
This is the monadic join operator for functions. join has type
Monad m => m (m a) => m a
and functions form a monad where the input type is fixed (i.e. ((->) a), so join has type:
(a -> (a -> b)) -> (a -> b)

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.

How do I choose the first tuple within a list and save the rest of the tuples in Erlang?

I want be able to input the following:
fun([{X,Y}, {A,B}, {M,N}]).
and only use the first tuple and save the others for later use. I tried defining it like this:
fun([{X|Y}, V]) ->
V.
But I just get a syntax error before the "|". "V" was just to try and output to see what was happening.
Is there any resources I can be pointed towards for some support with this? Or am I doing something really wrong?
func([{X,Y}| V]) -> %% fun is a keyword, you cannot use it as a function name
%% do some stuff with X, Y
V.
generally, if you want to apply the same function to all element of a list, it is good to use the lists module: (lists:foreach/2, lists:map/2, lists:foldl/2 ...) or a list comprehension
Res = [Fun(T) || T <- L]
wher Fun is the function to apply to each tuple T from the list L
you should write like this:
fun([{X, Y} | V]).
[{X, Y} | V] = [{X,Y}, {A,B}, {M,N}], then V = [{A,B}, {M,N}]

Guard for tuple of integers

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.

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.

Resources