I find myself writing loops (recursive functions) occasionally within assignments. It makes for awkward code like this:
let value =
let rec loop a =
if ... then a
else loop a.B
loop a
I know I could move the loop outside the let binding, but it’s only purpose is to compute the bound value.
So I thought I might abstract the loop into a separate function:
let loop f a =
let rec aux a =
match f a with
| Some b -> aux b
| None -> a
aux a
then I could do:
let value = a |> loop (fun a -> if ... then None else Some a.B)
Maybe that’s better–at least it looks like more like assignment than a function definition. Here are my questions:
- Is a recursive function in a
letbinding something of a code smell? - Is there a better way to refactor this?
- If not, could my
loopfunction be generalized further, or somehow improved?
These questions are a bit subjective, but here are my answers:
Here’s how I’d do it: