I have a general function that takes a lot of parameters
f : a -> b -> c -> d -> e -> f
I want to provide specialized functions that only take the last two parameters, but provide some fixed values for the first three.
g : d -> e -> f
h : d -> e -> f
Their implementation is something like the following
g = f someA someB someC
h = f someA' someB' someC'
This is all great of course, but when it comes to invoking those functions from C# it's a problem because their types don't get "prettified". Instead I get a bunch of nested FSharpFuncs.
I can avoid this problem by defining my functions like
g d e = f someA someB someC d e
h d e = f someA' someB' someC' d e
But this seems like a really simple, mechanical transformation so I'm wondering if there's an automated way to get the same result. Perhaps some attribute I can attach to them?
Technically speaking, the first and second options of how to write your g and h are not exactly the same. In the first case, f is applied to three arguments and the resulting new function is stored as an object in the value g.
Whereas in the second case, the function f is called with all 5 arguments every time with the values of someA, someB and someC being passed at the time of calling g.
For most cases, this distinction is not really relevant, but it becomes important when you want to cache some parts of your computation.
Long story short: The transformation has a slight semantic difference and therefore cannot really be done automatically. Just add the arguments to the new g and h.
Related
So functional programming is still pretty new to me and I'm trying to get to grips with the idea of avoiding holding (or rather mutating) "state". I think I'm confusing this concept with let bound variables. There are situations where I need to pass the result of a function to multiple other functions. For example, in the following code
let doSomething a b f g = ((a |> b |> f), (a |> b |> g))
the value b(a) is computed twice unnecessarily. What I want to do instead is
let result = b a
((f result), (g result))
However I feel like this is somehow violating a convention in functional programming? Does using let bound variables this way count as holding state? One alternative is
match a |> b with
| result -> ((f result), (g result))
But this feels like doing essentially the same as before. I wonder if this issue is due to a flaw in my functional programming approach, where perhaps these issues never arrive in the first place? Or maybe since let bound variables are immutable, using them in the former way is totally fine and I'm overthinking this completely? Apologies if this is a bit vague.
You can avoid the let binding by using a lambda expression
let doSomething a b f g = b a |> (fun x -> f x, g x)
I very frequently want to apply the same argument twice to a binary function f, is there a name for this convert function/combinator?
// convert: f: ('a -> 'a -> 'b) -> 'a -> 'b
let convert f x = f x x
Example usage might be partially applying convert with the multiplication operator * to fix the multiplicand and multiplier:
let fixedMultiplication = convert (*)
fixedMultiplication 2 // returns 4
That combinator is usually called a warbler; the name comes from Raymond Smullyan's book To Mock a Mockingbird, which has a bunch of logic puzzles around combinator functions, presented in the form of birds that can imitate each other's songs. See this usage in Suave, and this page which lists a whole bunch of combinator functions (the "standard" ones and some less-well-known ones as well), and the names that Smullyan gave them in his book.
Not really an answer to what it's called in F#, but in APL or J, it's called the "reflexive" (or perhaps "reflex") operator. In APL it is spelt ⍨ and used monadically – i.e. applied to one function (on its left). In J it's called ~, and used in the same way.
For example: f⍨ x is equivalent to x f x (in APL, functions that take two arguments are always used in a binary infix fashion).
So the "fixedMultiplication" (or square) function is ×⍨ in APL, or *~ in J.
This is the monadic join operator for functions. join has type
Monad m => m (m a) => m a
and functions form a monad where the input type is fixed (i.e. ((->) a), so join has type:
(a -> (a -> b)) -> (a -> b)
Can the function createTuple below be expressed pointfree?
let createTuple = fun v -> (v, v*2)
createTuple 2 |> printfn "%A" // (2,4)
The F# library does not provide many functions for writing code in point-free style (mainly because it is not particularly idiomatic way of writing F#), so you cannot write your createTuple function using just what is available in the core library.
If you really wanted to do this, you could define a couple of helper combinators for working with tuples:
/// Duplicates any given value & returns a tuple with two copies of it
let dup a = a, a
/// Transforms the first element using given function
let mapFst f (a, b) = (f a, b)
/// Transforms the second element (not needed here, but adding for symmetry)
let mapSnd f (a, b) = (a, f b)
With these, you could implement your function in a point-free way:
let createTuple = dup >> mapSnd ((*) 2)
This does the same thing as your function. I think it is significantly harder to decipher what is going on here and I would never actually write that code, but that's another issue :-).
I'm attempting to use Railway Oriented Programming principals http://fsharpforfunandprofit.com/rop/ and this http://indiedevspot.azurewebsites.net/2015/01/20/two-track-coding-rop-for-dummies-part-2/ for reference
I have successfully implemented this for most of the codebase, except now we are getting to putting items into SQL and wish to use ROP for validation of those types. The typical pattern is
Figure 1:
let createSomething a b c = {A = a; B = b; C = c}
let createValidSomething so =
createSomething
<!> validateFunction1 so.param1
<*> validateFunction2 so.param2
<*> ...so forth and so on
You will notice that createSomething is a function that returns a record type instantiation a -> b -> c -> a' -> b' -> c'
The SQL Type providers return a mutable type (non record). Lets look at my attempt to build a similar createSomething function
Figure 2:
let createSQS(a, b, c, d, e, f, g) =
let sqs = context.``[dbo].[Something]``.Create(a, b, c, d, e, f, g)
sqs
At this point, we know this already will not work, we have a->b->c->d->e->f->g->context.[dbo].[Something].Entity
I know I can have an intermediary record type and follow ROP principals, match on success/failure and then create my object off of the already validated. But does that not seem like too many steps?
Does anybody know of a good pattern for this? Ideally we could have a function similar to Figure1 that generates a Record Type that is compatible with the Type Providers.
I'm open to trying things and hanging out on Skype :).
Should your function createSQS not be better like this:
let createSQS a b c d e f g =
context.``[dbo].[Something]``.Create(a, b, c, d, e, f, g)
This one would have the needed signature of a->b->c->d->e->f->g->context.[dbo].[Something].Entity
So we came up with an answer at our dev meeting, and decided that we in fact WANT to execute each part in its own function. For the inner binds we invented our own operator; similar to plus (&&&) (which I will blog about on my site www.indiedevspot.com) and at the top level we ran with a normal bind.
Our top level code looks like this:
[<HttpPost>]
x.member Add(sa:Something) =
sa|>ValidateSomething
>>= converttoSSA
>>= persistSSA
We decided to separate the concerns due to independent testability of validation, conversion and persistence. The theory is that functional composition if made up of functions that are guaranteed to work, is itself inherently guaranteed to work (or have a much better chance).
If we went with the proposed method (which we have not yet solved), we would be mixing concerns of creation, validation and conversion. That would also end up creating an additional record type which was un-necessary.
I want to apply a function to both members of a homogenous tuple, resulting in another tuple. Following on from my previous question I defined an operator that seemed to make sense to me:
let (||>>) (a,b) f = f a, f b
However, again I feel like this might be a common use case but couldn't find it in the standard library. Does it exist?
I don't think there is any standard library function that does this.
My personal preference would be to avoid too many custom operators (they make code shorter, but they make it harder to read for people who have not seen the definition before). Applying function to both elements of a tuple is logically close to the map operation on lists (which applies a function to all elements of a list), so I would probably define Tuple2.map:
module Tuple2 =
let map f (a, b) = (f a, f b)
Then you can use the function quite nicely with pipelining:
let nums = (1, 2)
nums |> Tuple2.map (fun x -> x + 1)