F# standard function that invokes its argument - f#

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 ((|>) ())

Related

F#: Is there a function that can be used in place of the dot operator?

In F# one comes across this sort of thing:
let p = Earth().GetCountry1().GetPopulation()
Sometimes I find myself wanting to separate the argument from the function as is usually done in F#:
let p = ((Earth ()).GetCountry1 ()).GetPopulation ()
which requires many parentheses. Is there a function, or can someone think of one, which can be used in place of the dot operator, which facilitates a more elegant way of maintaining the space between function and argument -- something like this?
let dot method arg obj = obj.method arg
let p = Earth () |> dot GetCountry1 () |> dot GetPopulation ()
(My dot causes a compiler error.)
The original code is perfectly idiomatic F#. There's no need to change it.
However, sometimes you have an F# function pipeline and you need to call a method in the middle of it. The neatest way to do this is with a lambda:
aValue
|> aFunction parameter
|> anotherFunction
|> fun x -> x.Method()
|> oneLastFunction
The function you're trying to write is not possible in a statically typed language. This would need to be added as a language feature, or you can simply use a lambda as shown above.
First off, F# is a multi-paradigm language, so writing code in an OOP style is perfectly valid. If you are consuming C# libraries, this is very common.
I would suggest using the OOP-style (no space before arguments) for the OOP-style code and the functional-style (space after arguments) for the functional-style code.
There is no built-in mechanism for piping members in F#. This could be enabled in the future with the short-hand accessor suggestion or the lenses suggestion.
For now, the quickest solution for the functional-style is to write an anonymous function:
let p =
Earth ()
|> fun x -> x.getCountry1 ()
|> fun x -> x.getPopulation ()
If you do this frequently, it might be best to write a collection of helper functions:
let country1 x =
x.getCountry1 ()
let population x =
x.getPopulation ()
let p =
Earth ()
|> country1
|> population
You could probably implement your dot function using reflection but that would have a run-time overhead, which is probably not worth it.

Is there an F# operator to express this function?

I've got the following code:
let funcsAppliedToData data = funcs |> Seq.map (fun f -> f data)
Is there an operator to express the function defined in the brackets (or a neater way of writing the whole line, for that matter)?
You can rewrite this using a partial function application of the |> operator. The function you have:
(fun f -> f data)
Can also be written using the pipe operator:
(fun f -> data |> f)
You can treat the operator as a function:
(fun f -> (|>) data f)
Now you could use partial function application:
((|>) data)
This answers your question, but I don't think I would use this in practice. Writing the function explicitly may be a couple of characters longer, but I just find it much more readable. The pipe operator is not usually used in the above way and so anyone reading the code will basically have to reverse the process I described here to understand what's going on.

Right associative operator in F# [duplicate]

This question already has an answer here:
Function Application Operator ($) in F#?
(1 answer)
Closed 8 years ago.
Sometimes I have to write:
myList |> List.iter (fun x -> x)
I would really like to avoid the parentheses. In Haskell there is an operator for this ($)
It would look like this
myList |> List.iter $ fun x -> x
I created a custom operator
let inline (^!) f a = f a
and now I can write it like this
myList |> List.iter ^! fun x -> x
Is there something like this in F#?
There is no way to define custom operator with an explicitly specified associativity in F# - the associativity is determined based on the symbols forming the operator (and you can find it in the MSDN documentation for operators).
In this case, F# does not have any built-in operator that would let you avoid the parentheses and the idiomatic way is to write the code as you write it originally, with parentheses:
myList |> List.iter (fun x -> x)
This is difference in style if you are coming from Haskell, but I do not see any real disadvantage of writing the parentheses - it is just a matter of style that you'll get used to after writing F# for some time. If you want to avoid parentheses (e.g. to write a nice DSL), then you can always named function and write something like:
myList |> List.iter id
(I understand that your example is really just an example, so id would not work for your real use case, but you can always define your own functions if that makes the code more readable).
No, there's nothing like this in a standard F# library. However, you have almost done creating your own operator (by figuring out its name must start with ^).
This snippet by Stephen Swensen demonstrates a high precedence, right associative backward pipe, (^<|).
let inline (^<|) f a = f a
This single-liner from the linked page demonstrates how to use it:
{1..10} |> Seq.map ^<| fun x -> x + 3
And here is an example how to use it for multi-line functions. I find it most useful for real-world multi-liners as you no longer need to keep closing parenthesis at the end:
myList
|> List.map
^<| fun x ->
let ...
returnValue
In F# it's <|
So it would look like:
myList |> List.iter <| fun x -> x

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)

F# style - prefer () or <|

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.

Resources