vendredi 30 septembre 2016

Purescript Halogen, side effect (random number)

In a PureScript Halogen project, I would like to set the state to a random number, but how do I extract the value? The normal

r <- randomInt 1 10

does not compile when it's inside the eval function.

module Main where

import Prelude
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Random (randomInt, RANDOM)
import Halogen as H
import Halogen.HTML.Events.Indexed as HE
import Halogen.HTML.Indexed as HH
import Halogen.Util (runHalogenAff, awaitBody)

type State = { n::Int }

initialState :: State
initialState = { n: 3}

data Query a = NewRandom a

ui :: forall e. H.Component { n :: Int } Query e
ui =
    H.component { render, eval }
    where
    render :: State -> H.ComponentHTML Query
    render state =
        HH.button
            [ HE.onClick $ HE.input_ NewRandom ]
            [ HH.text $ show state.n ]


    eval :: Query ~> H.ComponentDSL State Query e
    eval (NewRandom next) = do
        H.modify (\state -> state { n=12 } )

        --I'd like to set n to a random number
        --but I don't know how.
        --let r = randomInt 1 10
        --H.modify (\state -> state { n=r } )
        pure next

main :: Eff (H.HalogenEffects ()) Unit
main =
    runHalogenAff do
    body <- awaitBody
    H.runUI ui initialState body




Aucun commentaire:

Enregistrer un commentaire