Purescript卤素,副作用(随机数)

时间:2016-09-30 09:51:29

标签: random state purescript halogen

在PureScript Halogen项目中,我想将状态设置为随机数,但如何提取值?正常

r <- randomInt 1 10

在eval函数内部时不编译。

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

1 个答案:

答案 0 :(得分:3)

您需要在ComponentDSL(当前有e类型var)的地方使用适当的monad才能实现,然后您可以使用H.fromEff解除{ {1}}:

randomInt

(旁白:如果您正在做有效的事情,即使您只需要module Main where import Prelude import Control.Monad.Aff (Aff) 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 eff. H.Component { n :: Int } Query (Aff (random :: RANDOM | eff)) 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 (Aff (random :: RANDOM | eff)) eval (NewRandom next) = do r <- H.fromEff $ randomInt 1 10 H.modify (\state -> state { n=r } ) pure next main :: forall eff. Eff (H.HalogenEffects (random :: RANDOM | eff)) Unit main = runHalogenAff do body <- awaitBody H.runUI ui initialState body ,最简单的方法是使用Eff作为Aff monad,就像使用{{1}时一样它期望它是ComponentDSL - 可以使用runUI模块中的Aff来更改monad,但是因为你只是在那里使用interpret无论如何,你也可以直接去Halogen.Component。)

请查看"Non-state effects" section of the guideAJAX example,了解有关interpret liftAff中运行效果的更多详情。