F# style - prefer () or <| - f#

Which of theese two alternatives do you find yourself using most often, and which is more "idiomatic"?
f arg (obj.DoStuff())
f arg <| obj.DoStuff()

Overall, I don't know that one or the other is more idiomatic.
Personally, the only time I use <| is with "raise":
raise <| new FooException("blah")
Apart from that, I always use parens. Note that since most F# code uses curried functions, this does not typically imply any "extra" parens:
f arg (g x y)
It's when you get into non-curried functions and constructors and whatnot that it starts getting less pretty:
f arg (g(x,y))
We will probably at least consider changing the F# languages rules so that high-precedence applications bind even more tightly; right now
f g()
parses like
f g ()
but a lot of people would like it to parse as
f (g())
(the motivating case in the original question). If you have a strong opinion about this, leave a comment on this response.

Because type inference works from left to right, a bonus of using |> is that it allows F# to infer the type of the argument of the function.
As a contrived example,
[1; 2; 3] |> (fun x -> x.Length*2)
works just fine, but
(fun x -> x.Length*2) [1; 2; 3]
complains of "lookup on object of indeterminate type".

I use () much much more often, but thats just preference, I'm pretty sure that <| is more idomatic, but I use () by habit.

Whenever possible, I much prefer |> because it reads from left to right.

Related

Is it possible to define an F# operator that applies multiple functions to a single argument (almost the opposite of the ||> operator)?

My attempt to do this is here (forgive the for loop - I was just curious to see if this was possible):
let (|>>) a (b : ('a -> unit) list) =
for x in b do
x a
but when I try to use it I get the error
That None of the types error message can occur if the function you're trying to use is defined further down the file or isn't imported correctly. Otherwise, your function definition seems ok.
I would discourage the use of a custom operator for this. I think they should be used very rarely. This one doesn't seem general enough to be worth defining and could make code hard to read. Here is one alternative:
[ printf "%A"; printfn "%A" ] |> List.iter ((|>) 1)
But it's even clearer and shorter to write out your operator definition inline:
for f in [ printf "%A"; printfn "%A" ] do f 1

F#, Pipe-forward first argument

Quite similar to this question:
F# pipe first parameter
I am currently learning F# and functional programming, and I want to know if there is an easy way to pipe-forward a first argument (instead of last argument).
For example, if I want to pipe forward the last argument, it looks very nice and clean:
[4;5;6]
|> List.append [1;2;3]
// Result: [1;2;3;4;5;6]
If I want to pipe-forward the first argument, I can use a "fun x ->" function, but I am just curious if there is a cleaner way.
[1;2;3]
|> fun x -> List.append x [4;5;6]
// Result: [1;2;3;4;5;6]
Thank you very much.
P.S. My coworker just helped me with this problem. But I would appreciate any help if you have any suggestions for an F# beginner. Thank you.
When the order of arguments is inconvenient, you can always transform the function itself to make it take the arguments in a different order:
let flip f x y = f y x
[1; 2; 3]
|> (flip List.append) [4; 5; 6]
Transforming functions is useful in many contexts. It is a functional programmer's bread and butter.
But in the end, I believe, readability is most important: programs are read incomparably more often than they are written. When I find myself in a similar situation, and I don't want to name the intermediate value or use a lambda expression for some reason, I define myself a function that would be intuitive to understand:
let prependTo a b = List.append b a
[1; 2; 3]
|> prependTo [4; 5; 6]
All the existing answers provide good solution to the problem.
However, I think that if you want to use pipe to specify the first argument of a function, most of the time, it is not a good idea and you should just use an ordinary call without pipes:
List.append [1;2;3] [4;5;6]
The reason is that the "piping pattern" lets you write code that performs series of transformations on some data structure (list, etc.). Libraries designed to support the piping pattern will take the "main input" as the last argument to support pipe.
If you are piping into an argument that is not last, it means that you are breaking this regularity, so you are no longer passing one data structure through a series of transformations. This will make your code confusing because "it looks like a pipe, but it is not really a pipe".
Of course, this is not always the case and there are situations where you need this, but as a rule of thumb, I'd only use pipe when it fits.
Just use a lambda:
[1;2;3] |> fun l -> l # [4;5;6]
or point-free:
[1;2;3] |> (#) <| [4;5;6] // or
([1;2;3], [4;5;6]) ||> (#)
or as a normal function:
let foo l = l # [4;5;6]
let bar = foo [1;2;3]
After asking my coworker, he suggested:
[1;2;3]
|> List.append
<| [4;5;6]
// Result: [1;2;3;4;5;6]
If you have any other suggestions to an F# beginner like me, I would greatly appreciate your help. Thank you.

F# standard function that invokes its argument

Probably a newbie question, but is there a standard function like
let apply f = f()
in F#?
No, there is not a standard function for this.
In most cases, just calling the function is shorter and more obvious than using apply would be, so I'm not entirely sure how this would be useful:
foo ()
apply foo
Now, you can also write application using |>, but that's not very nice either:
() |> foo
I guess the only place where apply would be useful is:
functions |> List.map apply
functions |> List.map (fun f -> f ())
Here, the version without apply is shorter, but I don't think it is worth having a named function in the library just for this one use case.
You could actually use |> here to avoid fun, which makes for a lovely piece of ASCII art :-), but not for something that I would ever want to see in my codebase:
functions |> List.map ((|>) ())

Seq.iter vs for - what difference?

I can do
for event in linq.Deltas do
or I can do
linq.Deltas |> Seq.iter(fun event ->
So I'm not sure if that is the same. If that is not the same I want to know the difference. I don't know what to use: iter or for.
added - so if that is the matter of choice I prefer to use iter on a top level and for is for closures
added some later - looking like iter is map + ignore - it's the way to run from using imperative ignore word. So it's looking like functional way ...
As others mentioned, there are some differences (iter supports non-generic IEnumerator and you can mutate mutable values in for). These are sometimes important differences, but most of the times you can freely choose which one to use.
I generally prefer for (if there is a language construct, why not use it?). The cases where iter looks nicer are when you have a function that you need to call (e.g. using partial application):
// I would write this:
strings |> Seq.iter (printfn "%c")
// instead of:
for s in strings do printfn "%c" s
Similarly, using iter is nicer if you use it at the end of some processing pipeline:
// I would write this:
inputs |> Seq.filter (fun x -> x > 0)
|> Seq.iter (fun x -> foo x)
// instead of:
let filtered = inputs |> Seq.filter (fun x -> x > 0)
for x in filtered do foo x
You can modify mutable variables from the body of a for loop. You can't do that from a closure, which implies you can't do that using iter. (Note: I'm talking about mutable variables declared outside of the for / iter. Local mutable variables are accessible.)
Considering that the point of iter is to perform some side effect, the difference can be important.
I personally seldom use iter, as I find for to be clearer.
For most of the situations, they are the same. I would prefer the first use. It looks clear to me.
The difference is that for in loop support IEnumerable objects, while Seq.iter requires that your collection (linq.deltas) is IEnumerable<T>.
E.g. MatchCollection class in .net regular expression inherits IEnumerable not IEnumerable<T>, you cannot use Seq.map or Seq.iter directly on it. But you can use for in loop.
It is the style of programming. Imperative vs using functional programming. Keep in mind that F# is not a pure functional programming language.
Generally, use Seq.Iter if it is a part of some large pipeline processing, as that makes it much more clearer, but for ordinary case I think the imperative way is clearer. Sometime it is a personal preference, sometimes it is other issues like performance.
for in F# is a form of list comprehension - bread and butter of functional programming while Seq.iter is a 'for side-effects only' imperative construct - not a sign of a functional code. Here what you can do with for:
let pairsTo n = seq {
for i in [1..n] do
for j in [i..n] do
if j%i <> 0 then yield (i,j) }
printf "%A" (pairsTo 10 |> Seq.toList)

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