考虑以下内容:
{-# 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
,但仅此而已,因此,感谢您的帮助。
这是您想要的吗?
{-# 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”:通过手动递归进行模式匹配,以处理连续的x
对y
,[Typex]
对,并且我已经使用map
connect
第一个Typex
中的每个x :: [Typex]
和第二个y :: [Typex]
。我还使用map
将新级别添加到坐标列表以生成新的connections
值。
这里使用的唯一镜头表情是:
tx & connections .~ (...)
用新值替换connections
的tx :: Typex
字段tx ^. level
获取当前tx :: Typex
的电平txs ^.. traverse.coordinate
,它获取列表coordinate
中所有Typex
值的txs :: [Typex]
字段,并将它们作为列表[(Int,Int)]
返回我认为,在镜头和“普通Haskell”之间的这种平衡是处理复杂转换的最佳方法。