4

i have seen in ruby as well powershell programming we can assign variables like a,b=b,a . it actually swaps the variable .

Is this possible in f# if so please guide me with some reference

Guy Coder
  • 23,219
  • 7
  • 62
  • 122
satish
  • 2,333
  • 3
  • 21
  • 37

1 Answers1

13

Generally, F# doesn't allow variable re-assignment. Rather it favors immutable named values via let bindings. So, the following is not possible:

let a = 3
a = 4

Unless you explicitly mark a as mutable:

let mutable a = 3
a <- 4

However, F# does allow in most situations variable "shadowing". The only restriction to this is that it can not be done on top level modules. But, within a function, for example, the following works fine:

let f () =
    let a,b = 1,2
    let a,b = b,a //"swap"
    a,b
Stephen Swensen
  • 21,945
  • 9
  • 78
  • 131
  • omg, I didn't realize F# in fact support "shadowing" besides in FSI. Though I am not sure if it is an abuse to harness shadowing to achieve simple `mutable`, it is convenient. – colinfang Sep 30 '13 at 12:02
  • 3
    On the contrary, I would always prefer shadowing over mutation. Shadowing has the same advantages as immutable data structures: different "versions" of your data are frozen in a certain scope. For example, shadowed variables are much easier to reason about when considering capture in a closure (in fact, F# doesn't allow capturing mutable variables in closures, but it does allow capturing immutable variables of type `ref`, which has the same effect). – Stephen Swensen Sep 30 '13 at 14:54