aoc2022/Common.hs

45 lines
1.0 KiB
Haskell

-- commonly used functions, types and etc
module Common where
import Data.List (findIndex, elemIndex)
import GHC.IO (unsafePerformIO)
import Control.DeepSeq (deepseq)
type Pos = (Int, Int)
type Grid a = [[a]]
(!!!) :: Grid a -> Pos -> a
(!!!) grid (x, y) = grid !! y !! x
findPos :: (Eq a) => a -> Grid a -> Maybe Pos
findPos target grid = do
y <- findIndex (target `elem`) grid
x <- elemIndex target (grid !! y)
Just (x, y)
gridMap :: (a -> b) -> Grid a -> Grid b
gridMap f = map (map f)
gridWidth :: Grid a -> Int
gridWidth = length . head
gridHeight :: Grid a -> Int
gridHeight = length
taxicabDist :: Pos -> Pos -> Int
taxicabDist (x1, y1) (x2, y2) = abs (x1 - x2) + abs (y1 - y2)
addPos :: Pos -> Pos -> Pos
addPos (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
subPos :: Pos -> Pos -> Pos
subPos (x1, y1) (x2, y2) = (x1 - x2, y1 - y2)
{-# NOINLINE debug #-}
debug :: Show a => a -> ()
debug = unsafePerformIO . print
trace :: Show b => b -> a -> a
trace s = deepseq (debug s)
count :: (a -> Bool) -> [a] -> Int
count f = length . filter f