Unlikely1879
Unlikely1879

Reputation: 95

Storing references to local variables in F#

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.

Upvotes: 0

Views: 64

Answers (1)

gileCAD
gileCAD

Reputation: 2493

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)

Upvotes: 1

Related Questions