2

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

h,f = 5 
4
  • Just out of curiosity: Is there some other language you have in mind that can do this? Commented Mar 12, 2018 at 6:43
  • @ChrisMartin Maybe this one. Commented Mar 12, 2018 at 6:50
  • @ChrisMartin in Python you can do h = f = 5. Commented Mar 12, 2018 at 9:10
  • @ChrisMartin In R you can even do f <- 5 -> h Commented Mar 12, 2018 at 19:46

1 Answer 1

5
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>
Sign up to request clarification or add additional context in comments.

2 Comments

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 I forgot that I could use repeat and the feature of lazy evaluation. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.