2

I have recently encountered a problem and hope one of you can help me.

I have an init Situation in Haskell that returns the initial state. However, I want to alternate between two start values on each call, however I don't quite understand how I should do that.

The below code is not my effective code, however I have simplified the snippet so that everything relevant I believe is there.

iVal1 :: Int
iVal1 = 1    

iVal2 :: Int
iVal2 = 2

data RandomSituation= RandomSituation Int

initSituation:: RandomSituation
initSituation = RandomSituation iVal1

I know currently I'm only assignign iVal1. However my goal would be= First call to "initSituation" should return "RandomSituation iVal1", the second call should return "RandomSituation iVal2", the third should return "RandomSituation iVal1" and so on...

EDIT:

As I had in mind: it is not possible. Easiest solution is to simply pass the old value as an argument, and them simply return the other one.

OffByOne
  • 47
  • 4
  • 3
    You'll either need to use the `State` monad, or work with a list like `cycle [iVal1, iVale2]`. You can't make the value of `initSituation` change just by looking at the current value. – chepner Dec 14 '21 at 20:19
  • 4
    You absolutely cannot do it as you describe. Haskell values are always the same. – Louis Wasserman Dec 14 '21 at 20:25
  • @Louis Wassermann exactly that is my problem. I know that this is not the sense of Haskell... However I think I ran into a Problem where I'm thinking totally the wrong way... Still I hoped somehow there is a workaround. However now I will rethink everything an change my code, so I do not run into this problem... With changing initSituation to initSituation:: Int ->state I can simply pass the old starting value and use the other one. Still thanks to everyone – OffByOne Dec 14 '21 at 21:04
  • @OffByOne One of the nice things about Haskell is , if you can figure out the functional way of expressing your problem, you can express it imperatively. The type system gives you an accessable way to refactor step-by-step into a functional solution. –  Dec 14 '21 at 23:56
  • 1
    *"pass the old value as an argument, and then simply return the other one"* and use *that* in the *next* call -- what is known as *"state passing paradigm"*. (see more under "how to think functional" [in this answer](https://stackoverflow.com/a/11923567/849891)) – Will Ness Feb 05 '22 at 04:15
  • 1
    Thanks @WillNess, did not know, that there is such a paradigm! – OffByOne Feb 05 '22 at 11:08
  • 1
    see more [here](https://stackoverflow.com/a/19951540/849891). :) – Will Ness Feb 05 '22 at 11:16

0 Answers0