4 ms·
In F#, most pipelined operations are expressed using the pipeline operator all the way. [1; 2; 3; 4] |> List.filter isEven |> List.sum That way you maintain t
by throwaway344 13y ago
In F#, most pipelined operations are expressed using the pipeline operator all the way.
[1; 2; 3; 4] |> List.filter isEven |> List.sum
That way you maintain the same operator order as you do in Scala, while maintaining some consistency with currying.
In addition, you can add other functions really simply while still maintaining the order.
[1; 2; 3; 4] |> List.filter isEven |> List.sum |> printfn "%i"
- virtualwhys 13y agoInteresting, in Scala you do: list filter isEven foreach println Which is, IMO, quite elegant, but then again I'm used to Scala and not yet at all familiar with F# and the reasoning behind the syntax.
- anonymoushn 13y agoList(1,2,3,4) filter isEven sum println error: type mismatch; found : Unit required: Numeric[?] List(1,2,3,4) filter isEven sum println ^
- virtualwhys 13y agoI didn't write what you wrote ;-) foreach takes a collection and applies some function (in this case println). I've actually had a use case for what you're trying do, so created an extension method on Any, which means you can then do, on Any-thing: (list filter isEven sum).echo I also hate typing "println". "echo" I can bang out instantly, and can do so on any expression, before or after its definition.
- ponzao 13y ago`sum` does not accept a function as a parameter, the original example had an `foreach` instead of `sum`. list filter isEven foreach println As a side note omitting that many commas and parenthesis is very rare at least based on the Scala projects I've worked on. The above example is equal to the one below: list.filter(isEven).foreach(println)
- virtualwhys 13y agoGood points, I tend to mix it up, rarely going parens-free style, but also not parens by default either. If you wanted to be really explicit you could do: list.filter(x=> isEven(x)).foreach(x=> println(x)) yuck ;-)
- ponzao 13y agoThat example is not quite equivalent, because now you are not passing `isEven` or `println` as arguments, you are passing anonymous functions that call `isEven` and `println`.