Any way to "open Seq" or similar effect? - f#

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)

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

formatting Composite function in f#

I have a recursive function in f# that iterates a string[] of commands that need to be run, each command runs a new command to generate a map to be passed to the next function.
The commands run correctly but are large and cumbersome to read, I believe that there is a better way to order / format these composite functions using pipe syntax however coming from c# as a lot of us do i for the life of me cannot seem to get it to work.
my command is :
let rec iterateCommands (map:Map<int,string array>) commandPosition =
if commandPosition < commands.Length then
match splitCommand(commands.[0]).[0] with
|"comOne" ->
iterateCommands (map.Add(commandPosition,create(splitCommand commands.[commandPosition])))(commandPosition+1)
The closest i have managed is by indenting the function but this is messy :
iterateCommands
(map.Add
(commandPosition,create
(splitCommand commands.[commandPosition])
)
)
(commandPosition+1)
Is it even possible to reformat this in f#? From what i have read i believe it possible, any help would be greatly appreciated
The command/variable types are:
commandPosition - int
commands - string[]
splitCommand string -> string[]
create string[] -> string[]
map : Map<int,string[]>
and of course the map.add map -> map + x
It's often hard to make out what is going on in a big statement with multiple inputs. I'd give names to the individual expressions, so that a reader can jump into any position and have a rough idea what's in the values used in a calculation, e.g.
let inCommands = splitCommand commands.[commandPosition]
let map' = map.Add (commandPosition, inCommands)
iterateCommands map' inCommands
Since I don't know what is being done here, the names aren't very meaningful. Ideally, they'd help to understand the individual steps of the calculation.
It'd be a bit easier to compose the call if you changed the arguments around:
let rec iterateCommands commandPosition (map:Map<int,string array>) =
// ...
That would enable you to write something like:
splitCommand commands.[commandPosition]
|> create
|> (fun x -> commandPosition, x)
|> map.Add
|> iterateCommands (commandPosition + 1)
The fact that commandPosition appears thrice in the composition is, in my opinion, a design smell, as is the fact that the type of this entire expression is unit. It doesn't look particularly functional, but since I don't understand exactly what this function attempts to do, I can't suggest a better design.
If you don't control iterateCommands, and hence can't change the order of arguments, you can always define a standard functional programming utility function:
let flip f x y = f y x
This enables you to write the following against the original version of iterateCommands:
splitCommand commands.[commandPosition]
|> create
|> (fun x -> commandPosition, x)
|> map.Add
|> (flip iterateCommands) (commandPosition + 1)

Better way for ' '|> Seq.isEmpty |> not'

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.

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