jxxcarlson/elm-tree-builder/4.0.1

NOTE: the latest version is 7.0.0

Tree.Build

This module provides tools for building a tree from a string or a list of blocks. As noted in the README, a tree is represented in text as an outline:

 > data = "1\n 2\n 3\n 4\n5\n 6\n 7"

To build a tree from it, we apply the function fromString:

fromString :
    node
    -> (Block -> a)
    -> String
    -> Result Error (Tree a)




> fromString "?" .content data
  Tree "0" [
        Tree "1" [Tree "2" [],Tree "3" [], Tree "4" []]
      , Tree "5" [Tree "6" [],Tree "7" []]
  ]

The first argument of fromString is a label for a default node. The second argument tells how to build a node from a Block. In the example, we are building a tree with string labels, so we need a function of type (Block -> String). Recall that

    type alias Block = { indent : Int, content: String }

Therefore

    .content : Block -> String

has the correct type. Here we use the representation of rose trees found in elm/rose-tree.

Note. The build functions described here here make a guess as to what the "quantum of indentation" is. The quantum of indentation is the largest integer Q such that all lines are indented by some multiple of Q. The guess used is either 1 or the number of leading spaces in the first line that has leading spaces.

fromString : a -> (Block -> a) -> String -> Result Error (Tree a)
> Build.fromString "?" .content "1\n 2\n 3"
  Ok (Tree "1" [Tree "2" [],Tree "3" []])
fromBlocks : a -> (Block -> a) -> List Block -> Result Error (Tree a)
forestFromString : a -> (Block -> a) -> (a -> Block) -> String -> Result Error (List (Tree a))

Example:

> Build.forestFromString
      "?"
      .content
      (\str -> {indent = 0, content = str})
      "1\n 2\n 3\na\n b\n c"
  Ok [  Tree "1" [Tree "2" [],Tree "3" []]
       ,Tree "a" [Tree "b" [],Tree "c" []]
     ]
a
-> (Block -> a)
-> (a -> Block)
-> List Block
-> Result Error (List (Tree a))
type Error
= EmptyBlocks
| BlocksNotWellFormed