I come from C# and find myself in love with the F# pattern matching syntax as it's simpler than C# switch and way more useful. I like to use it as much as possible, is there a performance or any other downside to using it in weird ways like in this example?
match 0 with
|_ when a<b -> a
|_ -> b
In this particular example, there will be no performance penalty. It is very likely that performance penalty will also be absent in other cases, but to be absolutely sure you'll have to look at the generated code with something like ILSpy.
I must also add that as you use F#, you'll find that if/then/else is also very nice. In C#, if/else feels kinda awkward, because it can't be used as expression, but in F# it is not the case, and so the awkwardness soon disappears.
let x = if a < b then a else b
It even reads like plain English! :-)
Related
I could not find an object choice in the standard libraries, that allows me to write
let safeDiv (numer : Choice<Exception, int>) (denom : Choice<Exception, int>) =
choice {
let! n = numer
let! d = denom
return! if d = 0
then Choice1Of2 (new DivideByZeroException())
else Choice2Of2 (n / d)
}
like in Haskell. Did I miss anything, or is there a third-party library for writing this kind of things, or do I have to re-invent this wheel?
There is no built-in computation expression for the Choice<'a,'b> type. In general, F# does not have a built-in computation expression for the commonly used Monads, but it does offer a fairly simple way to create them yourself: Computation Builders. This series is a good tutorial on how to implement them yourself. The F# library does often have a bind function defined that can be used as the basis of a Computation Builder, but it doesn't have one for the Choice type (I suspect because there are many variations of Choice).
Based on the example you provided, I suspect the F# Result<'a, 'error> type would actually be a better fit for your scenario. There's a code-review from a few months ago where a user posted an Either Computation Builder, and the accepted answer has a fairly complete implementation if you'd like to leverage it.
It is worth noting that, unlike in Haskell, using exceptions is a perfectly acceptable way to handle exceptional situations in F#. The language and the runtime both have a first-class support for exceptions and there is nothing wrong about using them.
I understand that your safeDiv function is for illustration, rather than being a real-world problem, so there is no reason for showing how to write that using exceptions.
In more realistic scenarios:
If the exception happens only when something actually goes wrong (network failure, etc.) then I would just let the system throw an exception and handle that using try ... with at the point where you need to restart the work or notify the user.
If the exception represents something expected (e.g. invalid user input) then you'll probably get more readable code if you define a custom data type to represent the wrong states (rather than using Choice<'a, exn> which has no semantic meaning).
It is also worth noting that computation expressions are only useful if you need to mix your special behaviour (exception propagation) with ordinary computation. I think it's often desirable to avoid that as much as possible (because it interleaves effects with pure computations).
For example, if you were doing input validation, you could define something like:
let result = validateAll [ condition1; condition2; condition3 ]
I would prefer that over a computation expression:
let result = validate {
do! condition1
do! condition2
do! condition3 }
That said, if you are absolutely certain that custom computation builder for error propagation is what you need, then Aaron's answer has all the information you need.
Is there a way to create first-class-like patterns in Erlang? I need to be able to create and pass patterns as args to other functions but I know patterns are not first class in Erlang. I also looked at Elixir but it doesn't seem to offer anything more as far as patterns go.
I was wondering if anyone has come up with a simple solution to this problem. I was thinking of trying to implement something like this:
% Instead of using variables, we would just use uppercase atoms which would serve as vars
% A passable pattern
Pattern = {ok, 'Result'}.
% Custom function to check for matches
match(pattern, {ok, [1,2,3]}). % => true
I am new to Erlang so perhaps this is completely unnecessary. Perhaps there is a library that does this sort of thing?
Any advice is greatly appreciated. Thanks in advance!
I don't know if something exists already that does what you want, but you can easily implement it like this:
-module (match).
-compile([export_all]).
-define(MF(S), fun(S) -> true; (_)->false end).
match(F,V) -> F(V).
test() ->
Pattern = ?MF({ok,_}),
false = match(Pattern,{error,reason}),
true = match(Pattern,{ok,[1,2,3]}).
You might want to look at Erlang match specifications, which I believe are the sorts of patterns you're asking about. They're used for matching values in Erlang's tables and databases as well as in Erlang tracing. You might find some inspiration there.
I'm not sure I see your entire problem but it seems that a predicate function would suite you well. It's pretty common way to parameterize generic functions with them in a functional language. Take a look at lists functions such as map, foldl, filter.
I ended up using Elixir's macro functionality to implement something similar to Erlang's match specs. The code looks much cleaner(since I am simply defining functions with patterns) and they work very similar to Erlang's match specs.
I have a module which does some non constrained minimization. I'd like to keep its' interface as simple as possible, so the best choice would be to reduce it to a single function something like: min_of( F ).
But as soon as it is brutal computation, i would have to deal with at least two constants: precision of minimization algorithm and maximum number of iterations, so it would not hang itself if target function doesn't have local minimum at all.
Anyways, the next best choice is: min_of( F, Iterations, Eps ). It's ok, but I don't like it. I would like to still have another min_of( F ) defined something like this:
min_of( F ) ->
min_of( F, 10000, 0.0001).
But without magic numbers.
I'm new to Erlang, so I don't know how to deal with this properly. Should i define a macros, a variable or maybe a function returning a constant? Or even something else? I found Erlang quite expressive, so this question seems to be more of a good practice, than technical question.
You can define macros like this
-define(ITERATIONS, 10000).
-define(EPS, 0.0001).
and then use them as
min_of(F, ?ITERATIONS, ?EPS).
You can use macros but you can also use in-lined functions.
-compile({inline, [iterations/0, eps/0]}).
iterations() -> 10000.
eps() -> 0.0001.
and then use it in the way
min_of(F) ->
min_of(F, iterations(), eps()).
The benefit is you can use all syntax tools without need of epp. In this case also calling of function is not performance critical so you can even go without inline directive.
First of all sorry for my English.
I would like to use a backtracking algorithm in Erlang. It would serve as a guessing to solve partially filled sudokus. A 9x9 sudoku is stored as a list of 81 elements, where every element stores the possible number which can go into that cell.
For a 4x4 sudoku my initial solution looks like this:
[[1],[3],[2],[4],[4],[2],[3],[1],[2,3],[4],[1],[2,3],[2,3],[1],[4],[2,3]]
This sudoku has 2 solutions. I have to write out both of them. After that initial solution reached, I need to implement a backtracking algorithm, but I don't know how to make it.
My thought is to write out the fixed elements into a new list called fixedlist which will change the multiple-solution cells to [].
For the above mentioned example the fixedlist looks like this:
[[1],[3],[2],[4],[4],[2],[3],[1],[],[4],[1],[],[],[1],[4],[]]
From here I have a "sample", I look for the lowest length in the solutionlist which is not equal to 1, and I try the first possible number of this cell and I put it to that fixedlist. Here I have an algorithm to update the cells and checks if it is still a solvable sudoku or not. If not, I don't know how to step back one and try a new one.
I know the pseudo code of it and I can use it for imperative languages but not for erlang. (prolog actually implemented backtrack algorithm, but erlang didn't)
Any idea?
Re: My bactracking functions.
These are the general functions which provide a framework for handling back-tracking and logical variables similar to a prolog engine. You must provide the function (predicates) which describe the program logic. If you write them as you would in prolog I can show you how to translate them into erlang. Very briefly you translate something like:
p :- q, r, s.
in prolog into something like
p(Next0) ->
Next1 = fun () -> s(Next0) end,
Next2 = fun () -> r(Next1) end,
q(Next2).
Here I am ignoring all other arguments except the continuations.
I hope this gives some help. As I said if you describe your algorithms I can help you translate them, I have been looking for a good example. You can, of course, just as well do it by yourself but this provides some help.
I'm in the process of learning F# and am enjoying it so far. Almost all of the examples online use the lightweight syntax (#light); however, also give a comment about it being on for said example in most cases.
Is it better to learn F# using #light enabled or disabled? I'm planning on eventually learning it w/o it turned on but am curious on if it would be better to learn it at the beginning or work on applying it after I know the core language more.
I'd definitely prefer learning F# with the #light syntax. The non-light version is sometimes useful for understanding some tricks about the F# syntax, but the #light syntax gives you much pleasant experience.
For example - using #light
let add a b c =
let ab = a + b
printfn "%d" ab
c - ab
Using non-light you can write the same thing like this:
let add a b c =
let ab = a + b in // 'in' keyword specifies where the binding (value 'ab') is valid
printfn "%d" ab; // ';' is operator for sequencing expressions
c - ab;; // ';;' is end of a function declaration
This for example shows that you cannot write something like:
let doNothing a b =
let sum = a + b in
There is an 'in' keyword at the end but the function doesn't have any body (because there is no expression following 'in'). In this case non-light syntax is sometimes interesting to understand what's going on... But as you can see, the #light code is a lot simpler.
The "#light" will probably become the default in a future release of the language, so I would learn it that way. I think it's rare for anyone to use the heavier syntax except for OCaml-compatibility (either when cross-compiling, or because the human sitting at the keyboard knows OCaml and is making a smoother transition to F#).
Because I learned F# from an OCaml book (and I use an OCaml mode for Emacs to edit F# code), I prefer to use the "heavy" syntax. I have worked with #light code, and of course most of the F# examples are written using the light syntax so having some general familiarity is useful. That said, it's quite a bit easier to switch from heavy to light than the other way around, so it's certainly not a bad idea to learn it using the heavy syntax.
I have come across the occasional annoying bug with heavy syntax being treated as a second class citizen (combine was broken for computation expressions a couple releases back), but these are pretty rare. Generally speaking, I don't think the differences are very significant and I need to look close to determine which syntax is being used when looking at code in isolation. YMMV.
If I remember correctly, book "Expert C#" mentions that #light will be the default when F# ships and that non-light syntax is intended for compatibility only.