Better way for ' '|> Seq.isEmpty |> not' - f#

I am just wondering if there is a better way to write:
|> Seq.isEmpty |> not
Something like:
|> not Seq.isEmpty

maybe you like?
|> (not << Seq.isEmpty)

I would probably go with what you have at the moment. It depends on the context - when this is the result of some larger function, I think the following looks good:
let someFunction () =
someData
|> Some pipeline
|> Seq.isEmpty
|> not
If I was writing this in some other context, I would most likely define a local variable and write something like this:
let local =
someData
|> Some pipeline
if not (Seq.isEmpty local) then
printfn "Not empty!"
The idea in #Carsten's answer is nice too, but I would be bit worried that it might look weird to people who are not familiar with this coding pattern. Understanding what's going on there is not very easy, in my opinion.

I'd say not. Instead, try to avoid functions like Seq.isEmpty, Seq.head, Seq.skip and so on when they undermine the lazyness or may lead to repeated enumeration of the sequence.
A prototypical implementation of Seq.isEmpty could be like
let isEmpty (xs : _ seq)=
use en = xs.GetEnumerator()
not <| en.MoveNext()
from which it is evident that in addition to its creation (and disposal) the enumerator has to advance itself once. An effort that will be repeated when you afterwards consume the sequence for good in case you have found it non-empty.
This could be mitigated by caching (Seq.cache), but you may ask as well if a sequence is still the right data structure for the task at hand.

Related

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

Any way to "open Seq" or similar effect?

a
|>Seq.map fixLine
|>Seq.map splitCells
|>Seq.map getName
|>Seq.where(fun a->not<|Seq.isEmpty a)
|>Seq.map fixName
Always find it annoying while keep lots of Seq. in lines. Suggest a good way to omit them...
For example, use List.map for lists, use just map for seq, or split them into different modules when I'm using seq and lists.
a
|>map fixLine
|>map splitCells
|>map getName
|>where(fun a->not<|isEmpty a)
|>map fixName
Looks really better.
You could also just define aliases for the functions you want:
let map = Seq.map
let where = Seq.filter
Or you could make it even more terse by defining your own operators:
let (|!>) s f = Seq.map f s
let (|*>) s f = Seq.filter f s
a
|!> fixLine
|!> splitCells
|!> getName
|*> (fun a->not<|isEmpty a)
|!> fixName
But at this point, your code becomes way too cryptic - i.e. someone looking at the code will have a hard time understanding what's going on.
And finally, you could make the original code look a bit better by noticing that a composition of maps is a map of composition:
a
|> Seq.map (fixLine >> splitCells >> getName)
|> Seq.filter (not << isEmpty)
|> Seq.map fixName
This is the solution that I personally would prefer.
In general, my personal experience shows that, despite the first impulse to "fix" the repetitiveness by making the repetitive parts themselves smaller, there is usually a better solution that would make your code not only look better, but better factored as well.
I don't think there is an easy way to avoid repeating the Seq - this is just one place where F# makes things a bit more explicit (so that you know what's going on).
But you can use the F# Core Fluent library which gives you a more C#-like syntax with .:
a.map(fixLine).map(splitCells).map(getName).filter(isEmpty >> not).map(fixName)

Avoid mutation in this example in F#

Coming from an OO background, I am having trouble wrapping my head around how to solve simple issues with FP when trying to avoid mutation.
let mutable run = true
let player1List = ["he"; "ho"; "ha"]
let addValue lst value =
value :: lst
while run do
let input = Console.ReadLine()
addValue player1List input |> printfn "%A"
if player1List.Length > 5 then
run <- false
printfn "all done" // daz never gunna happen
I know it is ok to use mutation in certain cases, but I am trying to train myself to avoid mutation as the default. With that said, can someone please show me an example of the above w/o using mutation in F#?
The final result should be that player1List continues to grow until the length of items are 6, then exit and print 'all done'
The easiest way is to use recursion
open System
let rec makelist l =
match l |> List.length with
|6 -> printfn "all done"; l
| _ -> makelist ((Console.ReadLine())::l)
makelist []
I also removed some the addValue function as it is far more idiomatic to just use :: in typical F# code.
Your original code also has a common problem for new F# coders that you use run = false when you wanted run <- false. In F#, = is always for comparison. The compiler does actually warn about this.
As others already explained, you can rewrite imperative loops using recursion. This is useful because it is an approach that always works and is quite fundamental to functional programming.
Alternatively, F# provides a rich set of library functions for working with collections, which can actually nicely express the logic that you need. So, you could write something like:
let player1List = ["he"; "ho"; "ha"]
let player2List = Seq.initInfinite (fun _ -> Console.ReadLine())
let listOf6 = Seq.append player1List list2 |> Seq.take 6 |> List.ofSeq
The idea here is that you create an infinite lazy sequence that reads inputs from the console, append it at the end of your initial player1List and then take first 6 elements.
Depending on what your actual logic is, you might do this a bit differently, but the nice thing is that this is probably closer to the logic that you want to implement...
In F#, we use recursion to do loop. However, if you know how many times you need to iterate, you could use F# List.fold like this to hide the recursion implementation.
[1..6] |> List.fold (fun acc _ -> Console.ReadLine()::acc) []
I would remove the pipe from match for readability but use it in the last expression to avoid extra brackets:
open System
let rec makelist l =
match List.length l with
| 6 -> printfn "all done"; l
| _ -> Console.ReadLine()::l |> makelist
makelist []

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)

How do you work with IList<> in F#?

I have a list of type IList<Effort>. The model Effort contains a float called Amount. I would like to return the sum of Amount for the whole list, in F#. How would this be achieved?
efforts |> Seq.sumBy (fun e -> e.Amount)
Upvoted the answers of Seq.fold, pipelined Seq.fold, and pipelined Seq.sumBy (I like the third one best).
That said, no one has mentioned that seq<'T> is F#'s name for IEnumerable<T>, and so the Seq module functions work on any IEnumerable, including ILists.
Seq.fold (fun acc (effort: Effort) -> acc + effort.Amount) 0.0 efforts
One detail that may be interesting is that you can also avoid using type annotations. In the code by sepp2k, you need to specify that the effort value has a type Effort, because the compiler is processing code from the left to the right (and it would fail on the call effort.Amount if it didn't know the type). You can write this using pipelining operator:
efforts |> Seq.fold (fun acc effort -> acc + effort.Amount) 0.0
Now, the compiler knows the type of effort because it knows that it is processing a collection efforts of type IList<Effort>. It's a minor improvement, but I think it's quite nice.

Resources