Identity function in Dart? - dart

Does Dart have an identity function? I understand that I can just write, (x) => x, but it would seem to be slightly easier to understand code if there was something like Function.identity?

Not in the core libraries (but possibly in some third-party package). It's trivial to make your own generic function:
T identity<T>(T x) => x;

Related

Idiomatic way to implement "services" in F#

When working in F# and implementing a "service" pattern, such as wrappers around web APIs or databases or USB gadgets, what's the idiomatic way to do this? My inclination is to use e.g. IDatabase and Database, ITwitter and Twitter, ICamera and Camera interfaces and classes just like in C#, allowing for easy test mocks. But I don't want to code "C# in F#" if that's not the standard way to do it.
I considered using DU's, to represent e.g. Camera | TestCamera, but that means putting all the mock code into the production codebase, which sounds horrible. But maybe that's just my OO background speaking.
I also considered making IDatabase a record of functions. I'm still open to that idea, but it seems a bit contrived. Plus it rules out the idea of ever using an IoC controller, or any "MEF-like" plugin capability (at least that I'm aware of).
What's the "idiomatic F#" way of doing this? Just follow the C# service pattern?
As mentioned in the other answer, using interfaces is fine in F# and that might be a good way to solve the problem. However, if you use more functional transformation-oriented style of programming, you may not need them.
Ideally, most of the actual interesting code should be transformations that do not perform any effects - and so they do not invoke any services. Instead, they just take inputs and produce outputs. Let me demonstrate using a database.
Using a IDatabase service, you might write something like this:
let readAveragePrice (database:IDatabase) =
[ for p in database.GetProducts() do
if not p.IsDiscontinued then
yield p.Price ]
|> Seq.average
When written like this, you can provide a mock implementation of IDatabase to test that the averaging logic in readAveragePrice is correct. However, you can also write the code like this:
let calculateAveragePrice (products:seq<Product>) =
[ for p in products do
if not p.IsDiscontinued then
yield p.Price ]
|> Seq.average
Now you can test calculateAveragePrice without any mocking - just give it some sample products that you want to process! This is pushing the data access out from the core logic to the outside. So you'd have:
database.GetProducts() |> calculateAveragePrice // Actual call in the system
[ Product(123.4) ] |> calculateAveragePrice // Call on sample data in the test
Of course, this is a simplistic example, but it shows the idea:
Push the data access code outside of the core logic and keep the core logic as pure functions that implement transformations. Then your core logic will be easy to test - given sample inputs, they should return the correct results!
While other people here write that there's nothing wrong with using interfaces in F#, I consider interfaces nothing more than an interop mechanism that enables F# to work with code written in the other .NET languages.
When I write code in C#, I follow the SOLID principles. When used together, the Single Responsibility Principle and the Interface Segregation Principle should ultimately drive you towards defining as small-grained interfaces as possible.
Thus, even in C#, properly designed interfaces should have only a single method:
public interface IProductQuery
{
IEnumerable<Product> GetProducts(int categoryId);
}
Furthermore, the Dependency Inversion Principle implies that "clients [...] own the abstract interfaces" (APPP, chapter 11), which means that artificial bundles of methods is a poor design anyway.
The only reason to define an interface like the above IProductQuery is that in C#, interfaces are still the best mechanism for polymorphism.
In F#, on the other hand, there's no reason to define a single-member interface. Use a function instead.
You can pass in functions as arguments to other functions:
let calculateAveragePrice getProducts categoryId =
categoryId
|> getProducts
|> Seq.filter (fun p -> not p.IsDiscontinued)
|> Seq.map (fun p -> p.Price)
|> Seq.average
In this example, you'll notice that getProducts is passed as an argument to the calculateAveragePrice function, and its type is not even declared. This fits beautifully with the principle of letting the client define the interface: the type of the argument is inferred from the client's usage. It has the type 'a -> #seq<Product> (because categoryId can be any generic type 'a).
Such a function as calculateAveragePrice is a higher-order function, which is a Functional thing to do.
There's nothing wrong with using interfaces in F#.
The textbook FP approach would be to have the client take functions that implement the logic of your component as arguments, but that approach doesn't scale nicely as the number of those functions grows. Grouping them together is a good idea as it improves readability, and using interfaces for that is an idiomatic way of doing it in .NET. It makes sense especially on the boundary of well-defined components, and I think the three interfaces you cite fit that description well.
I've seen DU's used roughly the way you described (providing both production and a fake implementation), but it doesn't sit well with me either.
If anything, records of functions are not idiomatic. They're a poor man's way of bundling together behaviour in FP languages, but if there's one thing object oriented languages do right, it's bundling together behaviour. Interfaces are just a better tool for the job, especially since F# lets you create implementations inline with object expression syntax.

Square root function in F#

How can we find the square root of a number in F#? Do we have a Sqrt function in F# just like we have Math.Sqrt() function in Java? I am a beginner in F# and couldn't find any significant help on the internet.
F# already has a sqrt function defined, so you should just be able to use:
sqrt x
where x is the value you wish to find the root of.
Yes, F# comes with a "sqrt" function. Called "sqrt" :)
http://blogs.msdn.com/b/dsyme/archive/2008/09/01/the-f-operators-and-basic-functions.aspx
Many more numerical libraries are available for F#, either open source (e.g. CodePlex) or from 3rd party vendors:
http://msdn.microsoft.com/en-us/library/vstudio/hh304372%28v=vs.100%29.aspx

cost of implementing pipeline operator

I'm following a language called 'elm' which is an attempt to bring a Haskel-esque syntax and FRP to Javascript. There has been some discussion here about implementing the pipeline operator from F# but the language designer has concerns about the increased cost (I assume in increased compilation time or compiler implementation complexity) over the more standard (in other FP langs at least) reverse pipeline operator (which elm already implements). Can anyone speak to this? [Feel free to post directly to that thread as well or I will paste back the best answers if no one else does].
https://groups.google.com/forum/?fromgroups=#!topic/elm-discuss/Kt0MbDyRpO4
Thanks!
In the discussion you reference, I see Evan poses two challenges:
Show me some F# project that uses it
Find some credible F# programmer talking about why it is a good idea and what costs come with it (blog post or something).
I'd answer as follows:
The forward pipe-idiom is very common in F# programming, both for stylistic (we like it) and practical (it helps type inference) reasons. Just about any F# project you'll find will use it frequently. Certainly all of my open source projects use it (Unquote, FsEye, NL found here). No doubt you'll find the same with all of the Github located F# projects including the F# compiler source itself.
Brian, a developer on the F# compiler team at Microsoft, blogged about Pipelining in F# back in 2008, a still very interesting and relevant blog which relates F# pipes to POSIX pipes. In my own estimation, there is very little cost to implementing a pipe operator. In the F# compiler, this is certainly true in every sense (it's a one-line, inline function definition).
The pipeline operator is actually incredibly simple - here is the standard definition
let inline (|>) a b = b a
Also, the . operator discussed in the thread is the reverse pipe operator in F# (<|) which enables you to eliminate some brackets.
I don't think adding pipeline operators would have a significant impact on complexity
In addition to the excellent answers already given here, I'd like to add a couple more points.
Firstly, one of the reasons why the pipeline operator is common in F# is that it helps to circumvent a shortcoming the way type inference is currently done. Specifically, if you apply an aggregate operation with a lambda function that uses OOP to a collection type inference will typically fail. For example:
Seq.map (fun z -> z.Real) zs
This fails because F# does not yet know the type of z when it encounters the property Real so it refuses to compile this code. The idiomatic fix is to use the pipeline operator:
xs |> Seq.map (fun z -> z.Real)
This is strictly uglier (IMO) but it works.
Secondly, the F# pipe operator is nice to a point but you cannot currently get the inferred type of an intermediate result. For example:
x
|> h
|> g
|> f
If there is a type error at f then the programmer will want to know the type of the value being fed into f in case the problem was actually with h or g but this is not currently possible in Visual Studio. Ironically, this was easy in OCaml with the Tuareg mode for Emacs because you could get the inferred type of any subexpression, not just an identifier.

Is the "expression problem" solvable in F#?

I've been watching an interesting video in which type classes in Haskell are used to solve the so-called "expression problem". About 15 minutes in, it shows how type classes can be used to "open up" a datatype based on a discriminated union for extension -- additional discriminators can be added separately without modifying / rebuilding the original definition.
I know type classes aren't available in F#, but is there a way using other language features to achieve this kind of extensibility? If not, how close can we come to solving the expression problem in F#?
Clarification: I'm assuming the problem is defined as described in the previous video
in the series -- extensibility of the datatype and operations on the datatype with the features of code-level modularization and separate compilation (extensions can be deployed as separate modules without needing to modify or recompile the original code) as well as static type safety.
As Jörg pointed out in a comment, it depends on what you mean by solve. If you mean solve including some form of type-checking that the you're not missing an implementation of some function for some case, then F# doesn't give you any elegant way (and I'm not sure if the Haskell solution is elegant). You may be able to encode it using the SML solution mentioned by kvb or maybe using one of the OO based solutions.
In reality, if I was developing a real-world system that needs to solve the problem, I would choose a solution that doesn't give you full checking, but is much easier to use.
A sketch would be to use obj as the representation of a type and use reflection to locate functions that provide implementation for individual cases. I would probably mark all parts using some attribute to make checking easier. A module adding application to an expression might look like this:
[<Extends("Expr")>] // Specifies that this type should be treated as a case of 'Expr'
type App = App of obj * obj
module AppModule =
[<Implements("format")>] // Specifies that this extends function 'format'
let format (App(e1, e2)) =
// We don't make recursive calls directly, but instead use `invoke` function
// and some representation of the function named `formatFunc`. Alternatively
// you could support 'e1?format' using dynamic invoke.
sprintfn "(%s %s)" (invoke formatFunc e1) (invoke formatFunc e2)
This does not give you any type-checking, but it gives you a fairly elegant solution that is easy to use and not that difficult to implement (using reflection). Checking that you're not missing a case is not done at compile-time, but you can easily write unit tests for that.
See Vesa Karvonen's comment here for one SML solution (albeit cumbersome), which can easily be translated to F#.
I know type classes aren't available in F#, but is there a way using other language features to achieve this kind of extensibility?
I do not believe so, no.
If not, how close can we come to solving the expression problem in F#?
The expression problem is about allowing the user to augment your library code with both new functions and new types without having to recompile your library. In F#, union types make it easy to add new functions (but impossible to add new union cases to an existing union type) and class types make it easy to derive new class types (but impossible to add new methods to an existing class hierarchy). These are the two forms of extensibility required in practice. The ability to extend in both directions simultaneously without sacrificing static type safety is just an academic curiosity, IME.
Incidentally, the most elegant way to provide this kind of extensibility that I have seen is to sacrifice type safety and use so-called "rule-based programming". Mathematica does this. For example, a function to compute the symbolic derivative of an expression that is an integer literal, variable or addition may be written in Mathematica like this:
D[_Integer, _] := 0
D[x_Symbol, x_] := 1
D[_Symbol, _] := 0
D[f_ + g_, x_] := D[f, x] + D[g, x]
We can retrofit support for multiplication like this:
D[f_ g_, x_] := f D[g, x] + g D[f, x]
and we can add a new function to evaluate an expression like this:
E[n_Integer] := n
E[f_ + g_] = E[f] + E[g]
To me, this is far more elegant than any of the solutions written in languages like OCaml, Haskell and Scala but, of course, it is not type safe.

When should we use FSharpFunc.Adapt?

Looking at the source in FSharp.Core and PowerPack, I see that a lot of higher-order functions that accept a function with two or more parameters use FSharpFunc.Adapt. For example:
let mapi f (arr: ResizeArray<_>) =
let f = FSharpFunc<_,_,_>.Adapt(f)
let len = length arr
let res = new ResizeArray<_>(len)
for i = 0 to len - 1 do
res.Add(f.Invoke(i, arr.[i]))
res
The documentation on FSharpFunc.Adapt is fairly thin. Is this a general best practice that we should be using any time we have a higher-order function with a similar signature? Only if the passed-in function is called multiple times? How much of an optimization is it? Should we be using Adapt everywhere we can, or only rarely?
Thanks for your time.
That's quite interesting! I don't have any official information (and I didn't see this documented anywhere), but here are some thoughts on how the Adapt function might work.
Functions like mapi take curried form of a function, which means that the type of the argument is compiled to something like FSharpFunc<int, FSharpFunc<T, R>>. However, many functions are actually compiled directly as functions of two arguments, so the actual value would typically be FSharpFunc<int, T, R> which inherits from FSharpFunc<int, FSharpFunc<T, R>>.
If you call this function (e.g. f 1 "a") the F# compiler generates something like this:
FSharpFunc<int, string>.InvokeFast<a>(f, 1, "a");
If you look at the InvokeFast function using Reflector, you'll see that it tests if the function is compiled as the optimized version (f :? FSharpFunc<int, T, R>). If yes, then it directly calls Invoke(1, "a") and if not then it needs to make two calls Invoke(1).Invoke("a").
This check is done each time you call a function passed as an argument (it is probably faster to do the check and then use the optimized call, because that's more common).
What the Adapt function does is that it converts any function to FSharpFunc<T1, T2, R> (if the function is not optimized, it creates a wrapper for it, but that's not the case most of the time). The calls to the adapted function will be faster, because they don't need to do the dynamic check every time (the check is done only once inside Adapt).
So, the summary is that Adapt could improve the performance if you're calling a function passed as an argument that takes more than 1 argument a large number of times. As with any optimizations, I wouldn't use this blindly, but it is an interesting thing to be aware of when tuning the performance!
(BTW: Thanks for a very interesting question, I didn't know the compiler does this :-))

Resources