当修改取决于索引时,如何使用镜头修改嵌套自定义数据类型的字段

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

考虑以下内容:

{-# LANGUAGE TemplateHaskell   #-}

import Control.Lens

data Typex = Typex 
    { _level       :: Int
    , _coordinate  :: (Int, Int)
    , _connections :: [(Int,(Int,Int))]
    } deriving Show
makeLenses ''Typex

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

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

setConnections :: [[Typex]] -> [[Typex]]
setConnections = ?

如何使用镜头以功能connections修改所有Typex[[Typex]] -> [[Typex]],以使每个Typex都如此

connections = [(level of Typex being modified +1, (x, y))] where
x,y = 0..(length of next [Typex] in [[Typex]])/2

X和y都需要经过下一个[Typex]的长度。如果可能,最后的[Typex]应该保持不变。因此,同一[Typex]中每个Typex的所有连接都相同。

setConnections $ buildNestedTypexs [(0,1),(1,1)]的输出应该是:

[ [ Typex { _level = 0
          , _coordinate = (0,0)
          , _connections = [(1,(0,0)), (1,(0,1)), (1,(1,0)), (1,(1,1))] }
  , Typex { _level = 0
          , _coordinate = (0,1)
          , _connections = [(1,(0,0)), (1,(0,1)), (1,(1,0)), (1,(1,1))] }
  , Typex { _level = 0
          , _coordinate = (1,0)
          , _connections = [(1,(0,0)), (1,(0,1)), (1,(1,0)), (1,(1,1))] }
  , Typex { _level = 0
          , _coordinate = (1,1)
          , _connections = [(1,(0,0)), (1,(0,1)), (1,(1,0)), (1,(1,1))] }
  ]
 ,[ Typex { _level = 1
          , _coordinate = (0,0)
          , _connections = [(0,(0,0))] }
  , Typex { _level = 1
          , _coordinate = (0,1)
          , _connections = [(0,(0,0))] }
  , Typex { _level = 1
          , _coordinate = (1,0)
          , _connections = [(0,(0,0))] }
  , Typex { _level = 1
          , _coordinate = (1,1)
          , _connections = [(0,(0,0))] }
  ]]

我想我需要import Control.Lens.Indexed,但仅此而已,因此,感谢您的帮助。

haskell nested indices lens custom-data-type
1个回答
3
投票

这是您想要的吗?

{-# LANGUAGE TupleSections #-}

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

这不是一个纯粹的镜头解决方案,但是我发现在使用镜头时,通常来说,让镜头去做一切并非总是一个好主意。这只会使事情难以编写且难以理解。

[在这里,我在很多地方都使用过“普通Haskell”:通过手动递归进行模式匹配,以处理连续的xy[Typex]对,并且我已经使用map connect第一个Typex中的每个x :: [Typex]和第二个y :: [Typex]。我还使用map将新级别添加到坐标列表以生成新的connections值。

这里使用的唯一镜头表情是:

  • [tx & connections .~ (...)用新值替换connectionstx :: Typex字段
  • [tx ^. level获取当前tx :: Typex的电平
  • txs ^.. traverse.coordinate,它获取列表coordinate中所有Typex值的txs :: [Typex]字段,并将它们作为列表[(Int,Int)]返回

我认为,在镜头和“普通Haskell”之间的这种平衡是处理复杂转换的最佳方法。

© www.soinside.com 2019 - 2024. All rights reserved.