From 1e3ed169712d07ac9f4fe4a93cf345cebdeb3505 Mon Sep 17 00:00:00 2001 From: George Thomas Date: Tue, 9 Dec 2025 00:02:54 +0000 Subject: [PATCH] Avoid unsafe list indexing --- haskell/Pre.hs | 10 ++++++++++ haskell/Puzzles/Day8.hs | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/haskell/Pre.hs b/haskell/Pre.hs index d7e1f2d..f3c28d1 100644 --- a/haskell/Pre.hs +++ b/haskell/Pre.hs @@ -36,6 +36,7 @@ module Pre ( Puzzle (..), digit, digitsToInt, + listIndex, ) where @@ -49,6 +50,7 @@ import "base" Prelude as BasePrelude hiding ( minimum, tail, unzip, + (!!), ) import Control.Applicative @@ -96,3 +98,11 @@ digit = fromIntegral . digitToInt <$> digitChar digitsToInt :: (Integral a) => [a] -> Int digitsToInt = snd . foldr (\b (p, acc) -> (10 * p, acc + fromIntegral b * p)) (1, 0) + +listIndex :: Int -> [a] -> Maybe a +listIndex n = + if n < 0 + then const Nothing + else \case + [] -> Nothing + x : xs -> if n == 0 then Just x else listIndex (n - 1) xs diff --git a/haskell/Puzzles/Day8.hs b/haskell/Puzzles/Day8.hs index 20193fc..a4b0f05 100644 --- a/haskell/Puzzles/Day8.hs +++ b/haskell/Puzzles/Day8.hs @@ -23,8 +23,8 @@ puzzle = . sortOn Down . map length . DS.toLists - . snd - . (!! n) + . maybe (error "not enough boxes") snd + . listIndex n . connectBoxes , uncurry . const $ TL.show