So, I'm an experienced OOP programmer (primarily C++), just now starting to dip my toes in with functional programming. From my understanding, in a purely functional paradigm, functions shouldn't have conditionals and should be broken down as much as possible using currying. Could someone provide me the "pure" functional version of the following example? Preferably using every strict technique that would be part of the functional paradigm:
let rec greatestCommonFactor a b =
if a = 0 then b
elif a < b then greatestCommonFactor a (b - a)
else greatestCommonFactor (a - b) b
The example function that you have supplied is already purely functional. When we talk about a function purity, what we are actually talking about is the property of functions being referentially transparent.
An expression is referentially transparent if it can be replaced with its value without altering the effect of the program. To give a simple example, imagine the function:
let add2 x = x + 2
Now, anywhere that the value add2 2 appears in our program, we can substitute the value 4 without altering the behaviour of the program.
Imagine now that we add some additional behaviour into the function that prints to the console:
let add2Print x =
printfn "%d" x
x + 2
Although the result of the function is the same as before, we can no longer perform value substitution with the value 4 without changing the behaviour of our program because our function has the additional side-effect of printing to the console.
This function is no longer referentially transparent and therefore not a pure function.
let rec greatestCommonFactor a b =
if a = 0 then b
elif a < b then greatestCommonFactor a (b - a)
else greatestCommonFactor (a - b) b
Looking at this function that you have supplied, no side-effects are involved in its execution. We will always get the same output value for given inputs a and b, therefore this is already a pure function.
To be clear, there is absolutely no issue with functions containing conditionals in functional programming. Often, however, we make use of pattern matching rather than if/elif/else expressions but in the example you have described, this is purely stylistic. An alternative expression of your function using pattern matching would be:
let rec greatestCommonFactor a b =
match a with
|0 -> b
|a' when a' < b -> greatestCommonFactor a' (b - a')
|a' -> greatestCommonFactor (a' - b) b
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)
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 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.
I don't understand how the Value Restriction in F# works. I've read the explanation in the wiki as well as the MSDN documentation. What I don't understand is:
Why, for example, this gives me a Value Restriction error (Taken from this question):
let toleq (e:float<_>) a b = (abs ( a - b ) ) < e
But ths doesn't:
let toleq e (a:float<_>) b = (abs ( a - b ) ) < e
This is generalized all right...
let is_bigger a b = a < b
but this isn't (it is specified as int):
let add a b = a + b
Why functions with implicit parameters generate Value Restriction:
this:
let item_count = List.fold (fun acc _ -> 1 + acc) 0
vs this:
let item_count l = List.fold (fun acc _ -> 1 + acc) 0 l
(Mind you, if I do use this function in a code fragment the VR error will be gone, but then the function will be specified to the type I used it for, and I want it to be generalized)
How does it work?
(I'm using the latest F#, v1.9.6.16)
EDIT
Better/recent info is here: Keeping partially applied function generic
(original below)
I think a pragmatic thing here is not to try to understand this too deeply, but rather to know a couple general strategies to get past the VR and move on with your work. It's a bit of a 'cop out' answer, but I'm not sure it makes sense to spend time understanding the intracacies of the F# type system (which continues to change in minor ways from release to release) here.
The two main strategies I would advocate are these. First, if you're defining a value with a function type (type with an arrow '->'), then ensure it is a syntactic function by doing eta-conversion:
// function that looks like a value, problem
let tupleList = List.map (fun x -> x,x)
// make it a syntactic function by adding argument to both sides
let tupleList l = List.map (fun x -> x,x) l
Second, if you still encounter VR/generalizing problems, then specify the entire type signature to say what you want (and then 'back off' as F# allows):
// below has a problem...
let toleq (e:float<_>) a b = (abs ( a - b ) ) < e
// so be fully explicit, get it working...
let toleq<[<Measure>]'u> (e:float<'u>) (a:float<'u>) (b:float<'u>) : bool =
(abs ( a - b ) ) < e
// then can experiment with removing annotations one-by-one...
let toleq<[<Measure>]'u> e (a:float<'u>) b = (abs ( a - b ) ) < e
I think those two strategies are the best pragmatic advice. That said, here's my attempt to answer your specific questions.
I don't know.
'>' is a fully generic function ('a -> 'a -> bool) which works for all types, and thus is_bigger generalizes. On the other-hand, '+' is an 'inline' function which works on a handful of primitive types and a certain class of other types; it can only be generalized inside other 'inline' functions, otherwise it must be pinned down to a specific type (or will default to 'int'). (The 'inline' method of ad-hoc polymorphism is how the mathematical operators in F# overcome the lack of "type classes".)
This is the 'syntactic function' issue I discussed above; 'let's compile down into fields/properties which, unlike functions, cannot be generic. So if you want it to be generic, make it a function. (See also this question for another exception to this rule.)
Value restriction was introduced to address some issues with polymorphism in the presence of side effects. F# inherits this from OCaml, and I believe value restriction exists in all ML variants. Here's a few more links for you to read, besides the links you cited. Since Haskell is pure, it's not subjected to this restriction.
As for your questions, I think question 3 is truly related to value restriction, while the first two are not.
No one, including the people on the F# team, knows the answer to this question in any meaningful way.
The F# type inference system is exactly like VB6 grammar in the sense that the compiler defines the truth.
Unfortunate, but true.
What is "monadic reflection"?
How can I use it in F#-program?
Is the meaning of term "reflection" there same as .NET-reflection?
Monadic reflection is essentially a grammar for describing layered monads or monad layering. In Haskell describing also means constructing monads. This is a higher level system so the code looks like functional but the result is monad composition - meaning that without actual monads (which are non-functional) there's nothing real / runnable at the end of the day. Filinski did it originally to try to bring a kind of monad emulation to Scheme but much more to explore theoretical aspects of monads.
Correction from the comment - F# has a Monad equivalent named "Computation Expressions"
Filinski's paper at POPL 2010 - no code but a lot of theory, and of course his original paper from 1994 - Representing Monads. Plus one that has some code: Monad Transformers and Modular Interpreters (1995)
Oh and for people who like code - Filinski's code is on-line. I'll list just one - go one step up and see another 7 and readme. Also just a bit of F# code which claims to be inspired by Filinski
I read through the first Google hit, some slides:
http://www.cs.ioc.ee/mpc-amast06/msfp/filinski-slides.pdf
From this, it looks like
This is not the same as .NET reflection. The name seems to refer to turning data into code (and vice-versa, with reification).
The code uses standard pure-functional operations, so implementation should be easy in F#. (once you understand it)
I have no idea if this would be useful for implementing an immutable cache for a recursive function. It look like you can define mutable operations and convert them to equivalent immutable operations automatically? I don't really understand the slides.
Oleg Kiselyov also has an article, but I didn't even try to read it. There's also a paper from Jonathan Sobel (et al). Hit number 5 is this question, so I stopped looking after that.
As previous answers links describes, Monadic reflection is a concept to bridge call/cc style and Church style programming. To describe these two concepts some more:
F# Computation expressions (=monads) are created with custom Builder type.
Don Syme has a good blog post about this. If I write code to use a builder and use syntax like:
attempt { let! n1 = f inp1
let! n2 = failIfBig inp2
let sum = n1 + n2
return sum }
the syntax is translated to call/cc "call-with-current-continuation" style program:
attempt.Delay(fun () ->
attempt.Bind(f inp1,(fun n1 ->
attempt.Bind(f inp2,(fun n2 ->
attempt.Let(n1 + n2,(fun sum ->
attempt.Return(sum))))))))
The last parameter is the next-command-to-be-executed until the end.
(Scheme-style programming.)
F# is based on OCaml.
F# has partial function application, but it also is strongly typed and has value restriction.
But OCaml don't have value restriction.
OCaml can be used in Church kind of programming, where combinator-functions are used to construct any other functions (or programs):
// S K I combinators:
let I x = x
let K x y = x
let S x y z = x z (y z)
//examples:
let seven = S (K) (K) 7
let doubleI = I I //Won't work in F#
// y-combinator to make recursion
let Y = S (K (S I I)) (S (S (K S) K) (K (S I I)))
Church numerals is a way to represent numbers with pure functions.
let zero f x = x
//same as: let zero = fun f -> fun x -> x
let succ n f x = f (n f x)
let one = succ zero
let two = succ (succ zero)
let add n1 n2 f x = n1 f (n2 f x)
let multiply n1 n2 f = n2(n1(f))
let exp n1 n2 = n2(n1)
Here, zero is a function that takes two functions as parameters: f is applied zero times so this represent the number zero, and x is used to function combination in other calculations (like add). succ function is like plusOne so one = zero |> plusOne.
To execute the functions, the last function will call the other functions with last parameter (x) as null.
(Haskell-style programming.)
In F# value restriction makes this hard. Church numerals can be made with C# 4.0 dynamic keyword (which uses .NET reflection inside). I think there are workarounds to do that also in F#.