Avoid unsafe list indexing
This commit is contained in:
parent
ea64a5af3e
commit
1e3ed16971
@ -36,6 +36,7 @@ module Pre (
|
|||||||
Puzzle (..),
|
Puzzle (..),
|
||||||
digit,
|
digit,
|
||||||
digitsToInt,
|
digitsToInt,
|
||||||
|
listIndex,
|
||||||
)
|
)
|
||||||
where
|
where
|
||||||
|
|
||||||
@ -49,6 +50,7 @@ import "base" Prelude as BasePrelude hiding (
|
|||||||
minimum,
|
minimum,
|
||||||
tail,
|
tail,
|
||||||
unzip,
|
unzip,
|
||||||
|
(!!),
|
||||||
)
|
)
|
||||||
|
|
||||||
import Control.Applicative
|
import Control.Applicative
|
||||||
@ -96,3 +98,11 @@ digit = fromIntegral . digitToInt <$> digitChar
|
|||||||
|
|
||||||
digitsToInt :: (Integral a) => [a] -> Int
|
digitsToInt :: (Integral a) => [a] -> Int
|
||||||
digitsToInt = snd . foldr (\b (p, acc) -> (10 * p, acc + fromIntegral b * p)) (1, 0)
|
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
|
||||||
|
|||||||
@ -23,8 +23,8 @@ puzzle =
|
|||||||
. sortOn Down
|
. sortOn Down
|
||||||
. map length
|
. map length
|
||||||
. DS.toLists
|
. DS.toLists
|
||||||
. snd
|
. maybe (error "not enough boxes") snd
|
||||||
. (!! n)
|
. listIndex n
|
||||||
. connectBoxes
|
. connectBoxes
|
||||||
, uncurry . const $
|
, uncurry . const $
|
||||||
TL.show
|
TL.show
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user