如何使用具有嵌套数据类型和镜头的iset?

问题描述 投票:0回答:1

我无法获取最后一个函数中的类型来排队。重点是通过仅依赖于三元组的索引的函数来设置连接中的所有价格倍数。元组中的原始Double值可以丢弃。

{-# LANGUAGE TemplateHaskell   #-}
{-# LANGUAGE TupleSections #-}

import Control.Lens

data Typex = Typex 
    { _level       :: Int
    , _coordinate  :: (Int, Int)
    , _connections :: [(Int, (Int, Int), Double)]  -- = (level, coordinate, price)
    } deriving Show
makeLenses ''Typex

initTypexLevel :: Int -> Int -> Int -> [Typex] 
initTypexLevel a b c = [ Typex a (x, y) [(0,(0,0),0.0)]
                       | x <- [0..b], y <- [0..c]
                       ]

buildNestedTypexs :: [(Int, Int)] -> [[Typex]]
buildNestedTypexs pts
     = setConnectionsx [ initTypexLevel i y y
                      | (i,(_,y)) <- zip [0..] pts
                      ]

setConnectionsx :: [[Typex]] -> [[Typex]]
setConnectionsx (x:rest@(y:_)) = map (connect y) x : setConnectionsx rest
  where connect :: [Typex] -> Typex -> Typex
        connect txs tx
          = tx & connections .~ (map ((tx ^. level) + 1, , 0.0) $ txs ^.. traverse.coordinate)
setConnectionsx lst = lst

setInitPrices  :: [[Typex]] -> [[Typex]]
setInitPrices  (x:rest) = map setIndexPrices x : setInitPrices  rest
  where setIndexPrices :: Typex -> Typex
        setIndexPrices tx =  n & connections .~ ??? -- using iset (?), set the price in every 3-tuple so that price = f (index of the 3-tuple) where f = i*2
setInitPrices  lst = lst
haskell indices lens custom-data-type
1个回答
0
投票

您可能正在寻找:

  where setIndexPrices :: Typex -> Typex
        setIndexPrices tx =  tx & connections .> traversed <. _3 .@~ f
        f i = 2 * fromIntegral i

[这里,.@~iset的运算符版本,.><.是用于组合索引光学元件的合成运算符.的变体。

如果考虑更简单的未分度光学元件:

connections . traverse . _3

此镜片取一个TypeX,专注于其_connections字段,遍历连接列表,并专注于每个连接的第三个字段(价格)。结果是光学元件按顺序遍历TypeX中的所有价格。

要对此光学元件进行索引,我们需要将未索引的traverse“升级”到索引的traversed。然后,我们要使用保留索引的合成运算符.><.,其中小于/大于符号指向光学元件中具有所需索引的部分。 (在具有多个索引的更复杂的场景中,可以使用<.>将来自两个光学元件的索引合并为索引对(i,j)。)

我们就是这样:

connections .> traversed <. _3

[它仍然按顺序遍历TypeX中的所有价格,但它也遍历了遍历的索引。

请注意,setInitPrices实际上是很容易写为“一次全部”镜头计算的功能之一。 map setIndexPrices和递归仅遍历嵌套列表,因此它们等效于光学组件traverse . traverse。因此,我们可以使用:

setInitPrices' :: [[Typex]] -> [[Typex]]
setInitPrices' = traverse .> traverse .> connections .> traversed <. _3 .@~ f
  where f i = 2 * fromIntegral i
© www.soinside.com 2019 - 2024. All rights reserved.