Skip to content

Instantly share code, notes, and snippets.

@throughnothing
Last active August 12, 2018 00:43
Show Gist options
  • Save throughnothing/2112cefaad795ed8ef4c7541fe701100 to your computer and use it in GitHub Desktop.
Save throughnothing/2112cefaad795ed8ef4c7541fe701100 to your computer and use it in GitHub Desktop.
Trie from list of words in Purescript
module Main where
import Prelude (($))
import Data.Map (Map, empty, lookup, insert)
import Data.Ord (class Ord)
import Data.String (toCodePointArray, CodePoint)
import Data.Foldable (foldl)
import Data.Maybe (fromMaybe)
import Data.List (List(..), (:), fromFoldable)
data Trie a = Trie (Map a (Trie a))
emptyTrie :: ∀ a. Trie a
emptyTrie = Trie empty
makeTrie :: ∀ c. Ord c => List c -> Trie c -> Trie c
makeTrie (Nil) trie = trie
makeTrie (x : xs) (Trie t) = Trie (insert x subtrie t)
where subtrie = makeTrie xs $ fromMaybe emptyTrie $ lookup x t
wordz :: List String -> Trie CodePoint
wordz xs = foldl f emptyTrie xs
where f t s = makeTrie (fromFoldable (toCodePointArray s)) t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment