Haskell/DG

Haskell Dogelang
import System.Environment
import Data.String
import Data.List
import Data.Char
import Data.Ord

data Tree a b = Node a b (Tree a b) (Tree a b) | Nil deriving (Show)

letters = "abcdefghijklmnopqrstuvwxyz"
filter_letters = filter (flip elem letters)
filter_words = filter (((<) 2) . length )

update t k def fn = case t of
  Node k' v' cl cr -> case compare k k' of
                      EQ -> Node k' (fn v') cl cr
                      LT -> Node k' v' (update cl k def fn) cr
                      GT -> Node k' v' cl (update cr k def fn)
  Nil -> Node k def Nil Nil

inorder t = case t of
  Node k v cl cr -> (inorder cl) ++ [(k, v)] ++ (inorder cr)
  Nil -> []

main = do
  args <- getArgs
  content <- readFile (args !! 0)

  let ws = filter_words $ map filter_letters $ words $ map toLower content
      t = foldl (\t w -> update t w 1 ((+) 1)) Nil ws
  print $ take 20 $ inorder t
  print $ take 20 $ sortBy (\a b -> compare (snd b) (snd a) ) $ inorder t
import "/sys/argv"
import "/collections/namedtuple"
import "/string/ascii_lowercase"



Node = namedtuple "Node" ("k", "v", "cl", "cr" )

letters = ascii_lowercase
filter_letters = (bind str.join "") <- bind filter (in letters)
filter_words = bind filter ((> 2) <- len)

update = t k def fn -> if
  (k', v', cl, cr = t) => if
              (k == k') => Node k' (fn v') cl cr
              (k < k')  => Node k' v' (update cl k def fn) cr
              (k > k')  => Node k' v' cl (update cr k def fn)
  t is None => Node k def None None

inorder = t -> if
  (k, v, cl, cr = t) => (inorder cl) + [(k, v)] + (inorder cr)
  t is None => []

main =  ->

  content = open $ argv !! 1 |>.read!
  words = (bind str.split sep:" ") <- (bind str.join " ") <- str.splitlines
  ws = filter_words $ map filter_letters $ words $ str.lower content
  t = foldl (t w -> update t w 1 (+ 1)) None ws
  print $ list $ take 20 $ inorder t
  print $ list $ take 20 $ sorted (inorder t) key:snd reverse:True

main!

Fpp


Comments and Discussion is provided by Disqus. They are tracking site and user interaction. Please refer to their privacy policy for information about data usage and retention. If you still want to look at comments or comment yourself, enable disqus by clicking here.

Previous: talk at Leipzig's Haskell conference HaL-10 , Next: Teaching theoretical computer science in January

links

social

Theme based on notmyidea