darrrr
darrrr

Reputation: 53

convert unique chars from string to Table Char Int

Im trying to convert a string to it's unique chars along with an integer counter to the following interface:

empty :: Table k v
insert :: Eq k => Table k v -> k -> v -> Table k v
exists :: Eq k => Table k v -> k -> Bool
lookup :: Eq k => Table k v -> k -> Maybe v
delete :: Eq k => Table k v -> k -> Table k v
iterate :: Table k v -> (b -> (k, v) -> b) -> b -> b
keys :: Table k v -> (b -> k -> b) -> b -> b
values :: Table k v -> (b -> v -> b) -> b -> b

My function so far is as follows:

auxCharacterCounts :: String -> Table Char Int
auxCharacterCounts (x:xs)
| length (x:xs) > 1 = (Table.insert Table.empty x (length $ filter (\y -> y == x) (x:xs)))

For example passing the string "sassa" to auxCharacterCounts and then running a lookup tablename 's' would yield Just 3

Giving us the indication that we have 3 occurences of the char 's' in the string "sassa". What im stuck at is wrapping my head on how to get the other characters, so to speak running lookup tablename 'a' would yield the result Just 2 (against the string "sassa")

Im not sure how to run this recursivly, can I pass the tail somehow? But if I did it will find the char 's' several times more and might result in unnessecary resource usage?

Cheers.

Upvotes: 0

Views: 178

Answers (1)

chi
chi

Reputation: 116174

Write an auxiliary function

increment :: (Eq k, Num v) => Table k v -> k -> Table k v

to add one to a value in the table. You can implement it using the table functions you have.

Then scan the string, and increment the table once for every character.

Upvotes: 1

Related Questions