3 ms·
You could use `Seq.scan` to get rid of the manual recursion: let n = 42. Seq.initInfinite float |> Seq.scan (fun x _ -> 0.5 * (x + n/x))
by daxfohl 13y ago
You could use `Seq.scan` to get rid of the manual recursion:
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 n
- darklajid 13y agoThank you for posting this. When 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.
- daxfohl 13y agoNote given appropriate `MyLinqExt.Scan` and `MyLinqExt.Pairwise`, you could write this in C# just as concisely.
- darklajid 13y agoHmm.. No. :) I guess that's discussed all over the thread here. I do like C# in general and agree that it can be used in a functional style, but 'just as concisely'? Can't agree with that. Needs the boilerplate (class definition, Main vs. .fsx for example), most keywords/methods seem to be longer (especially the Linq ones, SelectMany, FirstOrDefault etc) and there's no inherent way to build a pipeline as in "no |>". Obviously you can write quite similar code in C# and I would agree that C# doesn't make it especially hard, is even a roughly decent language for that sort of stuff. Still, the F# snippet looks a lot nicer to me. Which leads to .. Just a matter of preference, ymmv etc - there's no claim of superiority here.