1

Is there a way to assign the same value to multiple variables in Haskell? e.g something like this:

h,f = 5 

1 Answers1

4
Prelude> let [x, y] = replicate 2 5
Prelude> x
5
Prelude> y
5
Prelude>

You need replicate to "duplicate" a value. In this case, I duplicating 5 twice. [x, y] mean get x and y from a List. That list is [5, 5]. So, you got x = 5 and y = 5.

Well, I never did such behavior in the real world Haskell but you get what you want.

EDIT: We could use repeat function and the feature of lazy evaluation in the Haskell. Thanks to luqui.

Prelude> let x:y:_ = repeat 5
Prelude> x
5
Prelude> y
5
Prelude>
wisn
  • 974
  • 10
  • 17
  • 2
    If you want to avoid the possible pattern match error if you mismatch the length of the list with the number to replicate, use `repeat` instead: `let x:y:_ = repeat 5`. And I, too, have never seen this idiom in the wild, and suspect it to be rather futile for reasons @absolutezero mentions. – luqui Mar 12 '18 at 08:02
  • @luqui I forgot that I could use `repeat` and the feature of lazy evaluation. Thanks! – wisn Mar 12 '18 at 08:21