Skip to content

Instantly share code, notes, and snippets.

@TristanCacqueray
Last active August 25, 2023 20:00
Show Gist options
  • Save TristanCacqueray/fc8fb5cbba7a0391341e73b80a90b2e8 to your computer and use it in GitHub Desktop.
Save TristanCacqueray/fc8fb5cbba7a0391341e73b80a90b2e8 to your computer and use it in GitHub Desktop.
module NestedMapReduceTraversal where
data Section = Section String Bool [String]
data NumberedSection = NumberedSection Int String [(Int, String)]
deriving (Show, Eq)
numberSection :: [Section] -> [NumberedSection]
numberSection = go (1, 1)
where
go _ [] = []
go (sectionPos, lessonPos) (Section title reset lessons : rest) =
let lessonStart = if reset then 1 else lessonPos
numberedLessons = zip ([lessonStart ..]) lessons
numberedSection = NumberedSection sectionPos title numberedLessons
nextPos = (sectionPos + 1, lessonStart + length numberedLessons)
in numberedSection : go nextPos rest
example :: [Section]
example =
[ Section "Getting started" False ["Welcome", "Installation"]
, Section "Basic operator" False ["Addition / Subtraction", "Multiplication / Division"]
, Section "Advanced topics" True ["Mutability", "Immutability"]
]
expected :: [NumberedSection]
expected =
[ NumberedSection 1 "Getting started" [(1, "Welcome"), (2, "Installation")]
, NumberedSection 2 "Basic operator" [(3, "Addition / Subtraction"), (4, "Multiplication / Division")]
, NumberedSection 3 "Advanced topics" [(1, "Mutability"), (2, "Immutability")]
]
main = do
let got = numberSection example
if got /= expected
then mapM_ print got
else putStrLn "Ok!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment