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

时间:2020-03-05 12:06:52

标签: haskell nested indices haskell-lens custom-data-type

考虑以下几点:

{-# 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,但仅此而已,所有帮助都将受到赞赏。

1 个答案:

答案 0 :(得分: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 .~ (...),它将connections的{​​{1}}字段替换为新值
  • tx :: Typex,获取当前tx ^. level的级别
  • tx :: Typex,它提取列表txs ^.. traverse.coordinate中所有coordinate值的Typex字段,并将它们作为列表txs :: [Typex]返回

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

相关问题