I have some Run Length Encoding code that I wrote as an exercise
let rle s =
s
|> List.map (fun x -> (x, 1))
|> List.fold (fun acc x ->
match acc with
| [] -> [(x, 1)]
| h::(x, n) -> h::(x, n+1)
| h -> h::(x, 1)
)
|> List.map (fun (x, n) ->
match n with
| 1 -> x.ToString()
| _ -> x.ToString() + n.ToString()
)
The pattern h::(x, n) -> h::(x, n+1) fails to compile.
Does anyone know why?
It can’t compile because the second argument for
::pattern match must be alist, but here it is a tuple. In general, you seem to just misunderstandheadandtail. Head is the top element while tail is a list of following elements. Essentially swapping them does the trick:Note 1: As @pad noticed,
List.foldrequires one more argument, a “bootstrap” accumulator to start with. Obviously, it should be just an empty list,[].Note 2: you can’t directly match
x. Instead, you bind it tox0and comparex0withx.Note 3: matching empty list
[]is not necessary as it would happily work with the last pattern.