gpt4 book ai didi

haskell - 是否有 “dual”用于缩放?

转载 作者:行者123 更新时间:2023-12-02 10:11:11 25 4
gpt4 key购买 nike

zoom允许我们在实际定义了更多变量的上下文中使用仅使用某些状态变量的状态操作。

{-# LANGUAGE TemplateHaskell #-}

import Control.Lens

import Control.Monad.Trans.State
import Control.Monad.IO.Class

data Galaxy = Galaxy {
_solarSys :: SolarSystem
, _otherStars :: String
} deriving (Show)
data SolarSystem = SolarSystem {
_sun :: Float
, _planets :: Int
} deriving (Show)

makeLenses ''SolarSystem
makeLenses ''Galaxy

main = (`runStateT`Galaxy (SolarSystem 2e+30 8) "🌌🌌🌌") $ do
zoom solarSys $ do
sun -= 1e+23
planets += 1
liftIO . print =<< get
Galaxy {_solarSys = SolarSystem {_sun = 1.9999999e30, _planets = 9}, _otherStars = "🌌🌌🌌"}

But what if I want to do some stuff in an environment with only some state variables defined, and then run a computation that has some extra, local state-variables? Like

data Expedition = Expedition {
_environment :: SolarSystem
, _spacecraft :: Char
} deriving (Show)
makeLenses ''Exploration

main = (`runStateT`Galaxy (SolarSystem 2e+30 8) "Milky") $ do
zoom solarSys $ do
spectralFilter environment (spacecraft ???~= '🚀') $ do
spacecraft .= '🛰️'
environment . planets -= 1
liftIO . print =<< get

我怀疑宇宙飞船的初始化实际上需要一些其他光学器件,但我看不出是哪个。

最佳答案

这个功能怎么样?

cram :: Monad m => Iso' s' (s,x) -> x -> StateT s' m r -> StateT s m r
cram someiso extra action =
StateT (\small0 -> do let big0 = view (from someiso) (small0,extra)
(r,big) <- runStateT action big0
let (small,_) = view someiso big
pure (r,small))

“如果你让我相信扩展状态是小状态加上额外的东西,并且你给我一些初始的额外东西,我可以将扩展状态计算塞进小状态计算中。”

您必须编写一个Iso' Expedition (SolarSystem,Char)

关于haskell - 是否有 “dual”用于缩放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com