看看指南的非状态影响"部分,或 AJAX示例,详细了解eval中的运行效果.In a PureScript Halogen project, I would like to set the state to a random number, but how do I extract the value? The normalr <- randomInt 1 10does not compile when it's inside the eval function.module Main whereimport Preludeimport Control.Monad.Eff (Eff)import Control.Monad.Eff.Random (randomInt, RANDOM)import Halogen as Himport Halogen.HTML.Events.Indexed as HEimport Halogen.HTML.Indexed as HHimport Halogen.Util (runHalogenAff, awaitBody)type State = { n::Int }initialState :: StateinitialState = { n: 3}data Query a = NewRandom aui :: forall e. H.Component { n :: Int } Query eui = 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 nextmain :: Eff (H.HalogenEffects ()) Unitmain = runHalogenAff do body <- awaitBody H.runUI ui initialState body 解决方案 You need to use an appropriate monad with your ComponentDSL (where you have the e type var currently) to make it possible, and then you can use H.fromEff to lift the randomInt:module Main whereimport Preludeimport Control.Monad.Aff (Aff)import Control.Monad.Eff (Eff)import Control.Monad.Eff.Random (randomInt, RANDOM)import Halogen as Himport Halogen.HTML.Events.Indexed as HEimport Halogen.HTML.Indexed as HHimport Halogen.Util (runHalogenAff, awaitBody)type State = { n::Int }initialState :: StateinitialState = { n: 3}data Query a = NewRandom aui :: 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 nextmain :: forall eff. Eff (H.HalogenEffects (random :: RANDOM | eff)) Unitmain = runHalogenAff do body <- awaitBody H.runUI ui initialState body(Aside: If you're doing effectful things, even if you only need Eff, it's easiest to use Aff as the ComponentDSL monad, as when you use runUI it expects it to be Aff - it is possible to change the monad, using interpret in the Halogen.Component module, but since you'd just be using interpret liftAff there anyway, you may as well go straight to Aff.)Take a look at the "Non-state effects" section of the guide, or the AJAX example for more details on running effects in eval. 这篇关于Purescript卤素,副作用(随机数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!