I tried to write my own solution to the modified run-length encoding problem which appends ether a single element or an tuple into a list with a user defined type.
During the iteration I pattern-match the amount of occurrence of each element (which is computed with the helper method count) against 1 or _. However I get a warning at the second last line because the appending of a tuple is not accepted.
type 'a rle_type =
| One of 'a
| Many of int * 'a
(*hm for the amount of occurrences of a single element*)
let count e list = List.filter (fun x -> x=e ) list |> List.length
(*hm to delete dublicates*)
let rec compress = function
| a :: (b :: _ as t) -> if a = b then compress t else a :: compress t
| smaller -> smaller
let rle_mod list =
let rec aux lst enclst =
match lst with
| [] -> enclst
| h :: t -> match (count h list) with
| 1 -> aux t (h :: enclst)
| _ -> aux t ((count h list, h) :: enclst)
in aux (List.rev list |> compress)
I tried to manually specify the type of the list with (enclst : rle_type 'a) but it isn't working ether.
Do I have to modify the type definition to make it work?
As a reference for a better understanding, I already wrote the regular run-length encoding problem of the same site:
(*rle is using the same helper methods count and compress*)
let rle list =
let rec aux lst enclst =
match lst with
| [] -> enclst
| h :: t -> aux t ((count h list, h) :: enclst)
in aux (List.rev list |> compress) []
You've defined
so you should actually use it:
Notice that using
countis incorrect there, it counts all the occurrences ofhin the wholelist, not just the adjacent ones as the RLE should.