Skip to content

Instantly share code, notes, and snippets.

@jhrcek
Created May 10, 2017 17:04
Show Gist options
  • Save jhrcek/081a095b3dc817848647f9c89695b325 to your computer and use it in GitHub Desktop.
Save jhrcek/081a095b3dc817848647f9c89695b325 to your computer and use it in GitHub Desktop.
Tree labeling using State monad
module Tree
exposing
( Tree(Node)
, NodeId
, CollapsibleTree
, makeTree
)
--Using http://package.elm-lang.org/packages/folkertdev/elm-state/2.1.0
import State exposing (State)
import State
type Tree a
= Node a (List (Tree a))
type alias NodeId =
Int
type alias CollapsibleTree a =
Tree ( a, Bool, NodeId )
type alias IdGen a =
State NodeId a
makeTree : Tree a -> CollapsibleTree a
makeTree tree =
State.finalValue 0 (labelTree tree)
labelTree : Tree a -> IdGen (CollapsibleTree a)
labelTree (Node root children) =
State.map2
(\nid collapsibleChildren -> Node ( root, False, nid ) collapsibleChildren)
newNodeId
(State.traverse labelTree children)
newNodeId : IdGen NodeId
newNodeId =
State.modify (\x -> x + 1) |> State.andThen (\_ -> State.get)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment