by crntaylor · 12y ago · 0 comments
For example, say we want to write a function to compute square roots. A common approach to computing sqrt(n) is to start with a guess of x = 1.0, and keep replacing x with (0.5 * (x + n/x) until the relative difference between subsequent guesses is small enough.
sqrt n = loop x0 x1
where
loop x y = if converged x y
then y
else loop y (0.5 * (y + n/y))
converged x y = abs (x/y - 1) < 1e-10
x0 = 1.0;
x1 = 0.5 * (1.0 + 1.0/n)
That's good, but it has the test for convergence all mixed up with the logic for generating the guesses. What if we could factor out the code that generates an infinite sequence of guesses? sqrtGuesses n = go 1.0
where
go x = x : go (0.5 * (x + n/x))
Note that this works in Haskell because of laziness, but it's simple in any language that has a mechanism for delaying computations. Now we've decoupled the method for generating a sequence of guesses, we can write a function that checks for relative convergence converge (x:y:rest) = if abs (x/y - 1) < 1e-10
then y
else converge (y:rest)
and define the square root function in terms of these sqrt n = converge (sqrtGuesses n)
The logic of the program is now much cleaner, and we've got a useful function 'converge' which can be re-used in other parts of the program.This kind of 'turning inside out' is often possible in functional languages, often leads to more compact and more compositional code, and is one of the reasons that I enjoy programming functionally so much.
First, you really don't want to do that division x/y, which is slow, and which fails if y==0. It's much cheaper and safer to compare "abs(x-y) < 1e-10*y".
Also, you almost always want to compare (x-y) to an absolute convergence limit (in addition to your relative tolerance), in case x and y are very near zero.
Finally, if you really want a generic converge function that can be re-used elsewhere, you might want to allow for non-convergent processes. This requires tracking the number of iterations, and bailing when it gets too large.
By the way, now that your convergence function wants to know (x-y) rather than x and y individually, you might consider rewriting your logic functions to return the predicted change, rather than the final state. This avoids forcing a re-calculation of the change, which typically was already known in the logic function. It also avoids floating-point problems in which the calculated change x-y differs from the predicted change that produced y in the first place.
The last point does require changing the main code, but it's still easier to do with an external converge function like this.
I might be missing something, but won't your cheaper and safer fragment also fail when y is zero (or negative)?
And as you point out, you need to take the abs(y) as well, on the right-hand side.
Thanks for adding clarity.
sqrtGuesses n = iterate (\x -> (0.5 * (x + n/x))) 1.0EDIT: Ok, so obviously not "straight" from SICP. But pretty close.
Chapter 1: "Example: Square Roots by Newton's Method" http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html...
Which, by the way, is an excellent paper and totally worth reading.
http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pd...
[0] https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.htm...
[1] https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-27.htm...
(Sorry, it's just a not-so-well-known but awesome feature)
module Program =
let n = 42
let rec sqrtGuesses x = seq {
yield x
let next_x = 0.5 * (x + (float n / x))
yield! sqrtGuesses next_x }
sqrtGuesses 1.0
|> Seq.pairwise
|> Seq.pick (fun (x, y) ->
if abs (x - y) < 1E-10 then Some y else None)
|> System.Console.WriteLine
System.Console.WriteLine (sqrt (float n)) let n = 42.
Seq.initInfinite float
|> Seq.scan (fun x _ -> 0.5 * (x + n/x)) 1.0
|> Seq.pairwise
|> Seq.pick (fun (x, y) -> if abs <| x-y < 1E-10 then Some y else None)
|> printf "%f"
printf "%f" <| sqrt nWhen I saw the original version in F# I thought "I think I can do better" after a long absence from using F#. When I got back to my laptop and searched for the to-be-improved snippet I saw yours.
Now I'm hooked again.
For future reference "|>" like "$" in haskell is just short hand for a start and end parenthesis and end of expression or next instance of "|>" or "$".
So in Haskell:
sum $ filter (> 2) [0..10]
is a less noisy way of saying: sum(filter (>2) [0..10])
About the exclamation points, I believe it causes it to evaluate and has to do with ensuring the expression is evalauted. At least that is the case in haskell.As another commenter mentioned below, yield! has nothing to do with repeating the function name -- the name is repeated because it's a recursive function (i.e., a function which calls itself). So the sqrtGuesses function produces a sequence which emits (yields) the value it's given (x), computes the next value of x, stores it in the variable next_x, then emits all of the values in the sequence produced by calling sqrtGuesses for the next value of x (next_x).
The |> is called the "forward pipeline operator" in F#, and it's very simple -- whereas you normally call a function f with a value x by writing f x, you can swap the order of the arguments with |> to write x |> f. This effectively allows you to write nested function applications without all of the parentheses: f(g(h(x)) can instead be written x |> h |> g |> f or h x |> g |> f or whatever.
public static void Main()
{
const int n = 21;
Observable.Generate<double,double>(1, x=>true, x=> 0.5 * (x + (n/x)), x=>x )
.Scan(new {prv = 0d, cur = 0d}, (prev, curr) => new {prv = prev.cur, cur = curr})
.FirstAsync(_ => Math.Abs(_.cur - _.prv) < 1E-10)
.Select(_ => _.cur)
.Subscribe(Console.WriteLine);
// this is just to compare values, so is not part of the solution
Console.WriteLine(Math.Sqrt(n));
Console.ReadLine();
}
That's is, everything you need to run the program (technically one line of code, line breaks are for readability). And its non-destructive, has no side effects and is pretty easy to read.I would never argue that c# is a 'proper' functional language, but the poster above wrote in the style of idiomatic java, something a lot of c# devs do. I don't think c# has an 'idiomatic'. It is very flexible, and while never truly functional, can be also be used like a scala.