1
I want to implement a button that every time it is clicked changes state in Haskell. If it is on when press it should turn off and vice versa.
In c++ I would save the state in a global variable, but in Haskell I have no idea!
1
I want to implement a button that every time it is clicked changes state in Haskell. If it is on when press it should turn off and vice versa.
In c++ I would save the state in a global variable, but in Haskell I have no idea!
3
Haskell is a purely functional language. It is impossible to save the state of something. The only way to achieve what you want is to pass to a function two things at once: the previous state of the button and the user action. The function then must decide the new state of the button depending on the action.
A simple example:
-- Novo tipo para representar o botão
data Botao = Ligado | Desligado deriving (Eq, Show)
-- Novo tipo para representar uma acao
data Acao = Pressiona | Nada deriving (Eq, Show)
-- Recebe o estado de um botao, mais uma ação e retorna um novo estado
runBotao :: Botao -> Acao -> Botao
runBotao Ligado Pressiona = Desligado -- Se ligado e pressionado, muda para desligado
runBotao Desligado Pressiona = Ligado -- Se desligado e pressionado, muda para ligado
runBotao s Nada = s -- Se não houver ação, permanece no estado original
You can test in Ghci, for example:
ghci> Ligado `runBotao` Nada `runBotao` Pressiona `runBotao` Pressiona
Ligado
In this example, a button starts Ligado
, then there is no action, then it is pressed and finally it is pressed again.
To work with states more thoroughly and more widely, I recommend you read about the monad State
(unfortunately it seems that this chapter has not yet been translated into Portuguese).
Browser other questions tagged haskell
You are not signed in. Login or sign up in order to post.