Right associative operator in F# [duplicate] - f#

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

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

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.

Is there a built-in F# function to perform a side-effect on an item and return the item [duplicate]

...or in FSharpx?
let tee sideEffect =
fun x ->
do sideEffect x
x
The usage could be something like
f >> tee (printfn "F returned: %A") >> g >> h
Or is there another simple way to do this?
thanks!
The closest I've seen is actually in WebSharper. The definition is:
let inline ( |>! ) x sideEffect =
do sideEffect x
x
Usage:
(x |>! printf "%A") |> nextFunc
ExtCore includes a function called tap which does exactly what you want. I use it for primarily for inspecting intermediate values within an F# "pipeline" (hence the name).
For example:
[| 1;2;3 |]
|> Array.map (fun x -> x * 2)
|> tap (fun arr ->
printfn "The mapped array values are: %A" arr)
|> doOtherStuffWithArray
As far as I know, a function like this isn't defined anywhere in the F# core library - though the library is missing many standard functions that are quite easy to define yourself, so my recommendation would be just to add it somewhere in your project - your tee seems like the best way to go.
That said, I'd probably prefer using less declarative style if I need side-effects and write something like:
let fResult = f fInput
printfn "F returned: %A" fResult
fResult |> g |> h
This is just a matter of style, but I prefer declarative style for fully declarative code and imperative style when there are side-effects involved. As a bonus, using local variables makes debugging easier. But using a function like tee is an equally good alternative that many people in the F# community would prefer.

Composing 2 (or n) ('a -> unit) functions with same arg type

Is there some form of built-in / term I don't know that kinda-but-its-different 'composes' two 'a -> unit functions to yield a single one; e.g.:
let project event =
event |> logDirections
event |> stashDirections
let dispatch (batch:EncodedEventBatch) =
batch.chooseOfUnion () |> Seq.iter project
might become:
let project = logDirections FOLLOWEDBY stashDirections
let dispatch (batch:EncodedEventBatch) =
batch.chooseOfUnion () |> Seq.iter project
and then:
let dispatch (batch:EncodedEventBatch) =
batch.chooseOfUnion () |> Seq.iter (logDirections FOLLOWEDBY stashDirections)
I guess one might compare it to tee (as alluded to in FSFFAP's Railway Oriented Programming series).
(it needs to pass the same arg to both and I'm seeking to run them sequentially without any exception handling trickery concerns etc.)
(I know I can do let project fs arg = fs |> Seq.iter (fun f -> f arg) but am wondering if there is something built-in and/or some form of composition lib I'm not aware of)
The apply function from Klark is the most straightforward way to solve the problem.
If you want to dig deeper and understand the concept more generally, then you can say that you are lifting the sequential composition operation from working on values to work on functions.
First of all, the ; construct in F# can be viewed as sequential composition operator. Sadly, you cannot quite use it as one, e.g. (;) (because it is special and lazy in the second argument) but we can define our own operator instead to explore the idea:
let ($) a b = a; b
So, printfn "hi" $ 1 is now a sequential composition of a side-effecting operation and some expression that evaluates to 1 and it does the same thing as printfn "hi"; 1.
The next step is to define a lifting operation that turns a binary operator working on values to a binary operator working on functions:
let lift op g h = (fun a -> op (g a) (h a))
Rather than writing e.g. fun x -> foo x + bar x, you can now write lift (+) foo bar. So you have a point-free way of writing the same thing - just using operation that works on functions.
Now you can achieve what you want using the lift function and the sequential composition operator:
let seq2 a b = lift ($) a b
let seq3 a b c = lift ($) (lift ($) a b) c
let seqN l = Seq.reduce (lift ($)) l
The seq2 and seq3 functions compose just two operations, while seqN does the same thing as Klark's apply function.
It should be said that I'm writing this answer not because I think it is useful to implement things in F# in this way, but as you mentioned railway oriented programming and asked for deeper concepts behind this, it is interesting to see how things can be composed in functional languages.
Can you just apply an array of functions to a given data?
E.g. you can define:
let apply (arg:'a) (fs:(('a->unit) seq)) = fs |> Seq.iter (fun f -> f arg)
Then you will be able to do something like this:
apply 1 [(fun x -> printfn "%d" (x + 1)); (fun y -> printfn "%d" (y + 2))]

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)

Resources