Save function state in Haskell [closed]

1

I want to implement a button that whenever it is clicked changes its state into haskell. If it is turned on when you press it it should hang up and vice versa.

In c ++ I would save the state in a global variable, but in haskell I have no idea!

    
asked by anonymous 06.12.2017 / 04:49

1 answer

2

Haskell is a purely functional language. It is impossible to save the state of something. The only way to get what you want is to pass a function two things at once: the button's previous state and the user action. The function then decides the new button state 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 then pressed again.

To work with states in a more in-depth and more generalized way, I recommend that you read about monad State (unfortunately it seems that this chapter has not yet been translated into Portuguese).

    
06.12.2017 / 11:23