5

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
  • 24,501
  • 8
  • 71
  • 136
satish
  • 2,425
  • 3
  • 23
  • 40
  • possible duplicate: http://stackoverflow.com/questions/946977/f-how-do-you-return-multiple-values-and-assign-them-to-mutable-variables – BrokenGlass Apr 04 '11 at 03:51
  • I am learning python and imagine how cool F# could be if we allow: a, b <- b, a, x.[a], x.[b] <- x[b], x[a] So that swap is no longer needed. – colinfang Sep 30 '13 at 12:03

1 Answers1

14

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
  • 22,107
  • 9
  • 81
  • 136
  • 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