 # marosluuce's solution

## to Word Count in the LFE Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Given a phrase, count the occurrences of each word in that phrase.

For example for the input `"olly olly in come free"`

``````olly: 2
in: 1
come: 1
free: 1
``````

For installation and learning resources, refer to the exercism help page.

To run the provided tests, you will need `make`. Open a terminal window and run the following from the exercise directory:

``````make test
``````

You should now be able to see the results of the test suite for the exercise.

## Source

This is a classic toy problem, but we were reminded of it by seeing it in the Go Tour.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### word-count-tests.lfe

``````(defmodule word-count-tests
(behaviour ltest-unit)
(export all))

(include-lib "ltest/include/ltest-macros.lfe")

;; dict should be used to implement word-count:count/1.

(deftest count-one-word
(assert-count
"word"
'(#("word" 1))))

(deftest count-one-of-each
(assert-count
"one of each"
'(#("one"  1)
#("of"   1)
#("each" 1))))

(deftest count-multiple-occurrences
(assert-count
"one fish two fish red fish blue fish"
'(#("one"  1)
#("two"  1)
#("fish" 4)
#("red"  1)
#("blue" 1))))

(deftest ignore-punctuation
(assert-count
"car : carpet as java : javascript!!&@\$%^&"
'(#("car"        1)
#("carpet"     1)
#("as"         1)
#("java"       1)
#("javascript" 1))))

(deftest include-numbers
(assert-count
"testing, 1, 2 testing"
'(#("testing" 2)
#("1"       1)
#("2"       1))))

(deftest normalize-case
(assert-count
"go Go GO"
'(#("go"  3))))

(deftest prefix-punctuation
(assert-count
"!%%#testing, 1, 2 testing"
'(#("testing" 2)
#("1"       1)
#("2"       1))))

(deftest symbols-are-separators
(assert-count
"hey,my_spacebar_is_broken."
'(#("hey"      1)
#("my"       1)
#("spacebar" 1)
#("is"       1)
#("broken"   1))))

(defun assert-count (string expected)
(is-equal
(orddict:from_list expected)
(orddict:from_list (dict:to_list (word-count:count string)))))``````
``````(defmodule word-count
(export (count 1)))

(defun count (input)
(let ((words (to-words (string:to_lower input))))
(lists:foldl #'insert/2 (dict:new) words)))

(defun to-words (input)
(remove-empty
(re:split input "[^A-Za-z0-9]+" '(#(return list)))))

(defun remove-empty (words)
(lists:filter (lambda (word) (> (length word) 0)) words))

(defun insert (word acc)
(dict:update word (lambda (count) (+ count 1)) 1 acc))``````