packages feed

vmodel-0.1.0.0: src/VModel/Lane.hs

{-|
Module      : Lane
Description : A position-indexed list that supports move and duplicate
Copyright   : (c) Harley Eades, 2026
Maintainer  : harley.eades@gmail.com

t'Lane's are columns (or rows) of components that are allowed to be moved
and/or duplicated within their lane. A lane can be a column or a row. 
-}
module VModel.Lane 
    (-- ** Positions
     Position    
    ,lookupPos
    -- ** Lanes
    ,Lane
    ,empty
    ,insertAt
    ,append
    ,mapWithPos    
    ,join        
    -- ** Moving Items
    ,MoveError(..)
    ,move
    ,moveUp
    ,moveDown
    ,moveRight
    ,moveLeft
    -- ** Duplicating Items
    ,duplicate
    -- ** Searching for Items
    ,find
    -- ** Working with lists
    ,values
    ,fromList) where
import Data.Bifunctor (second, first)
import Data.List      qualified as DL

-- | The position of an item in the lane.
type Position = Int

-- | A lane is a position-indexed list of items. Positions start at @1@ (head
-- of the lane) and end at @length l@ (tail of the lane).
data Lane a = Lane [(Position, a)]
    deriving (Show,Eq)

instance Functor Lane where
    fmap :: (a -> b) -> Lane a -> Lane b
    fmap f (Lane s) = Lane $ fmap (second f) s

instance Applicative Lane where
  pure :: a -> Lane a
  pure x = Lane [(1,x)] 

  (<*>) :: Lane (a -> b) -> Lane a -> Lane b  
  (<*>) (Lane ((p,f):s1)) (Lane ((_,a):s2)) 
    = Lane $ (p,f a):r
        where
            Lane r = (Lane s1) <*> (Lane s2)
  (<*>) _ _ = empty

-- | Concatenates two lanes together and recalculates the positions.
append :: Lane a -> Lane a -> Lane a
append (Lane s1) (Lane s2) = Lane $ s1 ++ map (first calcPos) s2
    where
        calcPos p1 = p1 + length s1 

-- | Re calculates the positions in the given internal lane so that they start
-- from one and end at the length of the given list.
recalcPos :: [(Position,a)] -> [(Position,a)]
recalcPos = snd . aux
    where
        aux = foldl (\(pos,acc) (_,a) -> (pos+1,acc++[(pos+1,a)])) (0,[])

-- | Merges nested lanes and recalculates positions.
join :: Lane (Lane a) -> Lane a
join (Lane ((_,Lane s):seqs)) = Lane . recalcPos $ s ++ r
    where
        Lane r = (join $ Lane seqs)
join _ = empty

instance Monad Lane where  
    (>>=) :: Lane a -> (a -> Lane b) -> Lane b
    (>>=) s f = join . fmap f $ s

-- | The empty lane.
empty :: Lane a
empty = Lane []

-- | Get the values of a lane as a list.
values :: Lane a -> [a]
values (Lane s) = map snd s

-- | Map a function over a lane.
mapWithPos :: (Position -> a -> b) -> Lane a -> Lane b
mapWithPos f (Lane a) = Lane $ map f' a
    where
        f'(p,x) = (p,f p x)

-- | Returns the item at the given position.
lookupPos :: Position -> Lane a -> Maybe a
lookupPos p (Lane a) = lookup p a

-- | Find an item in the lane using either its position or a property on the
-- lanes items.
find :: ((Position,a) -> Bool) -> Lane a -> Maybe (Position,a)
find prd (Lane s) = DL.find prd s

-- | Insert into a lane based on a position starting at @1@.
-- - To insert at the head use position @1@.
-- - To insert at the tail use position @length s + 1@.
insertAt :: Position -> a -> Lane a -> Maybe (Lane a)
insertAt 0 _ _ = Nothing
insertAt 1 a (Lane []) = Just . Lane $ [(1,a)]
insertAt p a (Lane s) 
    | p < 1 || p > length s + 1 = Nothing
    | otherwise = Just . Lane $ before ++ (p,a) : map (first (+1)) after
    where
        (before,after) = splitAt (p-1) s

-- | Create a new lane from a list of items maintaining the order of the
-- input list.
fromList :: [a] -> Lane a
fromList = Lane . zip [1..]

-- | Move an item from the first position to the second position in the lane.
-- If the first position is smaller than the second the first position is moved
-- "down" (or "right" of) the lane, otherwise it is moved "up" (or "left" of)
-- the lane.
move :: Lane a -> Position -> Position -> Either MoveError (Lane a)
move lane fromPos toPos 
    | fromPos <= toPos = moveDown lane fromPos toPos
    | otherwise        = moveUp lane fromPos toPos

-- | If the input position is a valid position: 
-- @1 <= p <= length l@ where @l@ is the lane 
-- and @p@ is the position.
validPos :: Lane a -> Position -> Bool
validPos (Lane s) p
    = 1 <= p && p <= length s

-- | Errors that result from moving or duplicating items in the lane.
data MoveError
    = InvalidPositions     [Position]
    | FromPositionNotFound Position
    | ToPositionNotFound   Position
    | PositionNotFound     Position
    | InvalidPosition      Position
    deriving (Show,Eq)

-- | If we think of the lane as a vertical column, then this function moves an
-- an item from higher up (smaller index) the lane to a position lower down
-- (higher index) the lane. This function requires that the first position is
-- less-than-or equal to the second position.
moveDown :: Lane a -> Position -> Position -> Either MoveError (Lane a)
moveDown lane@(Lane s) fromPos toPos 
    | fromPos <= toPos && validPos lane fromPos && validPos lane toPos = do 
        let (before,after) = splitAt (fromPos-1) s
        case after of
            (fromPos',a):after' | fromPos == fromPos' 
                -> do let splitPos = toPos - length before - 1
                      let (before',after'') = splitAt (splitPos-1) after'
                      case after'' of
                        (toPos',a'):after''' | toPos == toPos' 
                            -> do let newBefore = (recalcPos $ before ++ before')
                                  let newAfter  = (toPos,a) : after'''
                                  pure . Lane $ newBefore ++ (toPos-1,a') : newAfter
                        _ -> Left $ ToPositionNotFound toPos
            _ -> Left $ FromPositionNotFound fromPos
    | otherwise = Left $ InvalidPositions [fromPos,toPos]

-- | This is an alias for 'moveDown'. 
moveRight :: Lane a -> Position -> Position -> Either MoveError (Lane a)
moveRight = moveDown

-- | If we think of the lane as a vertical column, then this function moves an
-- an item from lower down (higher index) the lane to a position higher up
-- (lower index) the lane. This function requires that the first position is
-- greater-than-or equal to the second position.
moveUp :: Lane a -> Position -> Position -> Either MoveError (Lane a)
moveUp lane@(Lane s) fromPos toPos 
    | fromPos >= toPos && validPos lane fromPos && validPos lane toPos 
        = do let (before1,after1) = splitAt (toPos-1) s
             case after1 of 
                (toPos1,a'):after2 | toPos == toPos1 
                    -> do let splitPos = fromPos - length before1 - 1
                          let (before2,after3) = splitAt (splitPos-1) after2
                          case after3 of
                            (fromPos2,a):after4 | fromPos == fromPos2 
                                -> do let newBefore = before1
                                      let newAfter  = (toPos1+1,a') : before2 ++ after4
                                      pure . Lane . recalcPos $ newBefore ++ (toPos1,a) : newAfter
                            _ -> Left $ FromPositionNotFound fromPos
                _ -> Left $ ToPositionNotFound toPos
    | otherwise = Left $ InvalidPositions [fromPos,toPos]

-- | This is an alias for 'moveUp'.
moveLeft :: Lane a -> Position -> Position -> Either MoveError (Lane a)
moveLeft = moveUp

-- | Duplicate the value at the given position and insert it after the given
-- position.
duplicate :: Lane a -> Position -> Either MoveError (Lane a)
duplicate lane@(Lane s) pos
    | validPos lane pos
        = do let (before,after) = splitAt (pos-1) s
             case after of
                (pos',a):after' | pos == pos' 
                    -> do let newAfter = (pos+1,a) : map (first (+1)) after'
                          pure . Lane $ before ++ (pos,a) : newAfter
                _ -> Left $ PositionNotFound pos
    | otherwise = Left $ InvalidPosition pos