Skip to content

Instantly share code, notes, and snippets.

@tomjaguarpaw
Last active August 30, 2023 08:10
Show Gist options
  • Save tomjaguarpaw/a77c012e7ddba58e5269b28613c101f3 to your computer and use it in GitHub Desktop.
Save tomjaguarpaw/a77c012e7ddba58e5269b28613c101f3 to your computer and use it in GitHub Desktop.
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -Wall #-}
module Main where
import Control.Lens (makeLenses, use, (%=), (.=))
import Control.Monad (when)
import Control.Monad.Trans.State.Strict (evalState)
import Data.Traversable (for)
data Lesson c = Lesson
{ name :: String,
lposition :: c
}
deriving (Show)
data Section c = Section
{ title :: String,
resetLessonPosition :: Bool,
lessons :: [Lesson c],
sposition :: c
}
deriving (Show)
sections :: [Section ()]
sections =
[ Section
{ title = "Getting started",
resetLessonPosition = False,
lessons =
[ Lesson {name = "Welcome", lposition = ()},
Lesson {name = "Installation", lposition = ()}
],
sposition = ()
},
Section
{ title = "Basic operator",
resetLessonPosition = False,
lessons =
[ Lesson {name = "Addition / Subtraction", lposition = ()},
Lesson {name = "Multiplication / Division", lposition = ()}
],
sposition = ()
},
Section
{ title = "Advanced topics",
resetLessonPosition = True,
lessons =
[ Lesson {name = "Mutability", lposition = ()},
Lesson {name = "Immutability", lposition = ()}
],
sposition = ()
}
]
data Counter = Counter {_lessonCounter :: Int}
$(makeLenses ''Counter)
initialCounter :: Counter
initialCounter = Counter {_lessonCounter = 1}
sections' :: [Section Int]
sections' = flip evalState initialCounter $ do
for (zip [1..] sections) $ \(sectionCounter, section) -> do
when (resetLessonPosition section) $
lessonCounter .= 1
lessons' <- for (lessons section) $ \lesson -> do
position <- use lessonCounter
lessonCounter %= (+ 1)
pure (lesson {lposition = position})
let section' = section {sposition = sectionCounter, lessons = lessons'}
pure section'
main :: IO ()
main = mapM_ print sections'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment