Rewriting Erlang to F #

I found a presentation from Don Syme that shows that

Erlang <
fac(0) -> 1 fac(N) -> N * fac(N-1). 

equivalent to f # 's

 let rec fac = function | 0 -> 1 | n -> n * fac (n-1) 

But it seems that there is no way to use pattern matching for another arrangement without losing type safety. For example. you can use list template matching, but then the type must be a common base type (for example, object ):

 let concat = function | [x;y] -> x.ToString() + y.ToString() | [x] -> x.ToString() 

Given that F # functions in modules do not support overloads, it looks like the only way to rewrite Erlang code in F # with static typing is to use static classes with method overloads instead of modules. Is there a better way to rewrite Erlang functions with different arity in F #?

In general, is it correct to say that mapping Erlang arguments is closer to overloading the .NET method (including C #), rather than matching to an F # pattern? Or there is no direct replacement between them, for example. in Erlang, there may be a function with different levels + guard:

 max(x) -> x. max(x,y) when x > y -> x. max(x,y) -> y. max(comparer, x, y) -> if comparer(x,y) > 0 -> x; true -> y end. 

In the latter case, the arguments are of different types. How would you rewrite it in F #?

+7
erlang f #
source share
1 answer

You can achieve something close to overload by slightly rethinking the problem. Instead of thinking of a function as an axis of variability, think of input as a variable part. If you do this, you will realize that you can achieve the same with discriminatory unification .

Here is a more contrived example than the one in the related article:

 type MyArguments = One of int | Two of int * int let foo = function | One x -> string x | Two (x, y) -> sprintf "%i%i" xy 

Using:

 > foo (One 42);; val it : string = "42" > foo (Two (13, 37));; val it : string = "1337" 

Obviously, instead of defining such a β€œstupid” type, as mentioned above, MyArguments , you should define a discriminatory union that makes sense in the model you are modeling.

+7
source share

All Articles