Created
August 25, 2023 19:25
-
-
Save goldfirere/ed1450872afd324ed656e2807b8dfcc0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE NoFieldSelectors, NamedFieldPuns, DuplicateRecordFields, DerivingStrategies #-} | |
{-# OPTIONS_GHC -Wall #-} | |
module UpdateSections where | |
import Data.List ( mapAccumL ) | |
newtype SectionPos = MkSP Int | |
deriving newtype (Show, Enum) | |
initialSectionPos :: SectionPos | |
initialSectionPos = MkSP 1 | |
data Section = MkS | |
{ title :: String | |
, reset_lesson_position :: Bool | |
, sec_position :: Maybe SectionPos | |
, lessons :: [Lesson] | |
} | |
deriving Show | |
newtype LessonPos = MkLP Int | |
deriving newtype (Show, Enum) | |
initialLessonPos :: LessonPos | |
initialLessonPos = MkLP 1 | |
data Lesson = MkL | |
{ name :: String | |
, less_position :: Maybe LessonPos | |
} | |
deriving Show | |
type Accumulator = (SectionPos, LessonPos) | |
renumberSections :: [Section] -> [Section] | |
renumberSections = snd . mapAccumL go_section (initialSectionPos, initialLessonPos) | |
where | |
go_section :: Accumulator -> Section -> (Accumulator, Section) | |
go_section (sec_pos, less_pos) sec@(MkS { reset_lesson_position, lessons }) = | |
((succ sec_pos, less_pos'), sec') | |
where | |
less_pos0 | reset_lesson_position = initialLessonPos | |
| otherwise = less_pos | |
(less_pos', lessons') = mapAccumL go_lesson less_pos0 lessons | |
sec' = sec { sec_position = Just sec_pos, lessons = lessons' } | |
go_lesson :: LessonPos -> Lesson -> (LessonPos, Lesson) | |
go_lesson less_pos less = (succ less_pos, less { less_position = Just less_pos }) | |
---------------------------- | |
exampleInput :: [Section] | |
exampleInput = [ | |
MkS { title = "Getting started" | |
, reset_lesson_position = False | |
, sec_position = Nothing | |
, lessons = [ MkL { name = "Welcome", less_position = Nothing } | |
, MkL { name = "Installation", less_position = Nothing } ] } | |
, MkS { title = "Basic operator" | |
, reset_lesson_position = False | |
, sec_position = Nothing | |
, lessons = [ MkL { name = "Addition / Subtraction", less_position = Nothing } | |
, MkL { name = "Multiplication / Division", less_position = Nothing } ] } | |
, MkS { title = "Advanced topics" | |
, reset_lesson_position = True | |
, sec_position = Nothing | |
, lessons = [ MkL { name = "Mutability", less_position = Nothing } | |
, MkL { name = "Immutability", less_position = Nothing } ] } ] | |
exampleOutput :: [Section] | |
exampleOutput = renumberSections exampleInput |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment