deleting duplicates tail recursively in OCaml - list

I tried to write my own solution for this exercise by iterating through a list with a empty complst list where all non duplicates are inserted into and then get returned.
I know it is a over complicated approach after looking up the solution but would still like to understand why the pattern matching does not work as intended:
let compress list =
let rec aux complst lst =
match lst with
| [] -> complst
| a :: (b :: c) -> if a = b then aux complst (b::c) else aux (a::complst) (b::c)
| x -> x
in aux [] list;;
val comp : 'a list -> 'a list = <fun>
Regardless of the input, the output is always a list with only the last element:
compress [1;1;2;2;3];;
- : int list = [3]
compress [1;2;3];;
- : int list = [3]

Pattern matching
Your pattern-matching matches against three patterns:
The empty list: []
The list with at least two elements: a :: (b :: c)
A catch-all, which must by process of elimination be a list with a single element.
Consider what happens when we evaluate your example:
compress [1; 1; 2; 2; 3]
aux [] [1; 1; 2; 2; 3]
aux [] [1; 2; 2; 3]
aux [1] [2; 2; 3]
aux [1] [2; 3]
aux [2; 1] [3]
[3]
Oops, as soon as it hit lst being [3] it just returned it.
Let's rewrite your function to handle that single element list by adding to complst.
let compress lst =
let rec aux complst lst =
match lst with
| [] -> complst
| [x] -> aux (x::complst) []
| a :: (b :: c) ->
if a = b then aux complst (b::c)
else aux (a::complst) (b::c)
in
aux [] list
Now:
compress [1; 1; 2; 2; 3]
aux [] [1; 1; 2; 2; 3]
aux [] [1; 2; 2; 3]
aux [1] [2; 2; 3]
aux [1] [2; 3]
aux [2; 1] [3]
aux [3; 2; 1] []
[3; 2; 1]
Clean up and reversing the resulting list
Of course, there are also ways to clean up your code a bit using a conditional guard and _ for values you don't need to bind names to. You probably also want to reverse your accumulator.
let compress lst =
let rec aux complst lst =
match lst with
| [] -> List.rev complst
| [x] -> aux (x::complst) []
| a :: (b :: _ as tl) when a = b -> aux complst tl
| a :: (_ :: _ as tl) -> aux (a::complst) tl
in
aux [] lst
Fold
When you see this pattern of iterating over a list one element at a time and accumulating a new value, you can usually map that pretty well to List.fold_left.
let compress lst =
List.(
fold_left
(fun i x ->
match i with
| (x'::_) when x = x' -> i
| _ -> x::i)
[] lst
|> rev
)
Because List.fold_left can only be aware of one element at a time on the list, the function we pass as its first argument can't be aware of the next element in the list. But it is aware of the accumulator or "init" value. In this case that's another list, and we can pattern match out that list.
If it's not empty and the first element is equal to the current element we're looking at, don't add it to the result list. Otherwise, do add it. This also handles the first element case where the accumulator is empty.
Kudos on creating a tail-recursive solution to this problem!

The problem with your code here is mainly the last part, which corresponds to when you have the last element in your list so here [3], and you return that list with this single element.
What you need to do instead is append it to complst like this :
let compress list =
let rec aux complst lst =
match lst with
| [] -> complst
| a :: (b :: c ) -> if a=b then aux complst (b::c) else aux (a::complst) (b::c)
| x::e -> x::complst
in aux [] list;;
val comp : 'a list -> 'a list = <fun>
Now you can check with the given example :
compress [1;1;2;2;3];;
- : int list = [3; 2; 1]
Hope it helps you understand your mistake better.
Note regarding comments:
you should keep the [] case, because although it can only happen in one scenario, it is still a valid input meaning it must be kept!.

Related

How to generate all possible splitting of a list?

Given a list: [1; 2; 3], how can I generate all possible splits:
[
[ [1; 2; 3] ];
[ [1]; [2; 3] ];
[ [1]; [2]; [3] ];
[ [1; 2]; [3] ]
]
I have no real attempt yet, I don't know how to start
EDIT : attempt
I tried to do it step by step but it's kinda messy
and I couldn't do mergeFirst, without mergeFirst it gives : [[[1]; [2; 3]]; [[1]; [2]; [3]]]
Am I on the right path ? I don't think my code will work if the list contains more than 3 elements too ...
let split = function
| [] -> []
| x::y -> [[x::y]] # [[[x]] # [[List.hd y]]]
(* let mergeFirst a = function
... *)
let addtoseperatelist a list =
List.map (fun t -> [[a]] # t) (list)
let rec generateAllSplit = function
| [] -> []
| [x;y] -> split (x::y::[])
| x::y -> addtoseperatelist x (generateAllSplit y) # (mergeFirst x (generateAllSplit y))
let myList = [[1;2;3]]
let _ = generateAllSplit myList
Until you get farther with your analysis, this isn't actually an OCaml question. It's more a question about breaking down a problem recursively.
One good way to solve problems that feel recursive is to imagine that you already had the solution. If you had your split function already, it would return the following for the tail of your list ([2; 3]):
[ [[2; 3]]; [[2]; [3]] ]
Is there a way to process this smaller result into your desired final result? Yes. There are two things you can do with [1]: you can merge it with the first element of the returned lists, or you can add it as a separate list. That gives you the four values of the desired result. You should be able to prove to yourself that his always gives the right answer. (Or maybe it doesn't, you'll have to check.)
If your given list has fewer than 2 elements, the result is obvious. You can probably combine this with the above recursive processing to get the answer.
You are on the right track. The merge first is still missing, which you have to do with pattern matching because the empty list is a special case. In my code that is (function [] -> [[x]] | z::zs -> (x::z)::zs) ys
The one element list is also a special case for split because it only has one result. If you would solve that recursively you would get [[x]; []] and [[x] # []] == [[x]].
Instead of adding to the recursive results and merging to the recursive results and then appending the two resulting lists I decided to use a fold_left and construct the adding and merging of each sub list in parallel. Then you can :: the results instead of append:
let myList = [1;2;3]
let rec split = function
| [] -> [[[]]]
| [x] -> [[[x]]]
| (x : int)::xs ->
List.fold_left
(fun (acc : int list list list) (ys : int list list) ->
([x] :: ys) (* add to separate list *)
:: (function [] -> [[x]] | z::zs -> (x::z)::zs) ys (* merge first *)
:: acc
)
[]
(split xs)
let res = split myList;;
val myList : int list = [1; 2; 3]
val split : int list -> int list list list = <fun>
val res : int list list list =
[[[1]; [2; 3]]; [[1; 2; 3]]; [[1]; [2]; [3]]; [[1; 2]; [3]]]

insert element in all positions of a list in OCaml

Trying to insert a number in all positions of the list, result being a list of lists.
something like:
insert 4 [1; 2; 3] = [[4; 1; 2; 3]; [1; 4; 2; 3]; [1; 2; 4; 3]; [1; 2; 3; 4]]
My idea is to apply Map on the list with a function that returns a list.
resulting in list of lists. like [f 1; f 2 ; f3] (I know will only have 3 lists, but just want to get this working first)
let insert (x : 'a) (ls : 'a list): 'a list list =
let aux p =
List.fold_left
(fun f2 acc q ->
if p = q then List.append acc x::[q]
else List.append acc q::[])
[] ls
in
List.map aux ls
Hope is, function aux will return a list with x inserted in the right place.
The problem is, List.map f1 ls line is assuming ls is 'a list list even though it is defined as 'a list
Any ideas please?
To actually answer your question, instead of providing you with different methods to reach your goal (you wanted to know what is actually wrong with your code, not how one could solve the problem.):
signature of fold_left is ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a = <fun>. Instead of ('a -> 'b -> 'a) your provide it with fun f2 acc q -> ... = ('a -> 'b -> 'c -> 'a). Just remove the f2 and you're fine.
put brackets around stuff like x::[q], or use ##.
Your code:
let insert (x : 'a) (ls : 'a list): 'a list list =
let aux p =
List.fold_left
(fun f2 acc q ->
if p = q then List.append acc x::[q]
else List.append acc q::[])
[] ls
in
List.map aux ls
Working code:
let insert (x : 'a) (ls : 'a list): 'a list list =
let aux p =
List.fold_left
(fun acc q ->
if p = q then List.append acc (x::[q])
else List.append acc (q::[]))
[] ls
in
List.map aux ls
For input insert 4 [1;2;3]this returns int list list = [[4; 1; 2; 3]; [1; 4; 2; 3]; [1; 2; 4; 3]]. This is almost what you wanted. The rest can be fixed by you :).
Note:
The Error that the Compiler throws is: Error: This expression has type 'a list but an expression was expected of type 'b list -> 'b list list. For the next time, just think about what happened. You provide fold_left with ('a -> 'b -> 'c -> 'a); which is not "wrong", but not what you want. You could write it as ('a -> ('b -> 'c) -> 'a). This means the acc-value is some 'a and the value of the fold is a function 'b -> 'c. This explains the error-message :).
Try breaking this problem down.
First hurdle: can you insert an element at a given index in a list? The start might look like:
let rec insert lst pos v =
(* ... *)
Well, we know if the position is 0, it should go at the front.
let rec insert lst pos v =
match pos with
| 0 -> v :: lst
| _ -> (* ... *)
If it's not 0 then you'd need to append the first element in lst to the result of inserting into the tail of the list at pos - 1.
Of course, the devil is in the details. What happens if you try insert [1; 2; 3; 4] 7 5? You need to find a way to check for situations like this.
If you can get this function to work, you then just need to iterate from 0 to the length of the list, inserting the new value into the list.
List.init would work nicely.
List.(
let lst = [1; 2; 3; 4] in
let len = length lst + 1 in
init len (fun i -> insert lst i 5)
)
And as a result, if you wrote insert correctly, you should get:
[[5; 1; 2; 3; 4]; [1; 5; 2; 3; 4]; [1; 2; 5; 3; 4];
[1; 2; 3; 5; 4]; [1; 2; 3; 4; 5]]
This should do the trick:
let rec insert v l =
match l with
| [] -> [[v]]
| x::xs -> (v::l) :: (List.map (List.cons x) (insert v xs))
Adding an explanation, had to think about this a while too:
For an empty list there is only one way to insert v and [[v]] is the result.
For a list x::xs first insert v at all positions in xs: insert v xs, which gives a list of lists. Then for each list add x back to the front: List.map (List.cons x) .... This gives all the results where v is inserted after x. So last construct the list where v is added before x: v::l. Adding that to the front of the list of lists gives the final result.

Delete elements between two occurrences in list

I have to make a function that take a list and return the list but without the elements betweens the occurences.
For example: [1; 2; 3; 4; 2; 7; 14; 21; 7; 5] -> [1; 2; 7; 5]
I imagined that to make this I will take the head of the list, and then see
if there is another occurrence in the tail, so I browse the list and when I found the occurrence, I delete everything between them and I keep just one of them.
First I tried something like this:
let rec remove list = match list with
| [] -> []
| h::t -> if(List.mem h t) then
(*Here I would like to go through the list element by element to
find the occurence and then delete everything between*)
else
remove t
So for the part I don't succeed to do, I made a function which allows to slice a list between two given points, just like so:
let slice list i k =
let rec take n = function
| [] -> []
| h :: t -> if n = 0 then [] else h :: take (n-1) t
in
let rec drop n = function
| [] -> []
| h :: t as l -> if n = 0 then l else drop (n-1) t
in
take (k - i + 1) (drop i list);;
(*Use: slice ["a";"b";"c";"d";"e";"f";"g";"h";"i";"j"] 2 3;;*)
I also have this function that allows me to get the index of points in the list:
let index_of e l =
let rec index_rec i = function
| [] -> raise Not_found
| hd::tl -> if hd = e then i else index_rec (i+1) tl
in
index_rec 0 l ;;
(*Use: index_of 5 [1;2;3;4;5;6] -> return 4*)
But I don't really know how to combine them to get what I expect.
here is what I made :
let rec remove liste =
let rec aux l el = match l with
| [] -> raise Not_found
| x :: xs -> if el = x then try aux xs el with Not_found -> xs
else aux xs el in
match liste with
| [] -> []
| x :: xs -> try let r = x :: aux xs x in remove r with Not_found -> x :: remove xs;;
my aux function return the list which follow the last occurence of el in l. If you have any question or if you need more explanation just ask me in comment
A version that uses an option type to tell if an element appears further on in the list:
let rec find_tail ?(eq = (=)) lst elem =
match lst with
| x :: _ when eq x elem -> Some lst
| _ :: xs -> find_tail ~eq xs elem
| [] -> None
let rec remove ?(eq = (=)) lst =
match lst with
| [x] -> [x]
| x :: xs -> begin
match find_tail ~eq xs x with
| Some tail -> x :: remove ~eq (List.tl tail)
| None -> x :: remove ~eq xs
end
| [] -> []
Also lets you specify a comparison function (Defaulting to =).

Implementing collect for list in F#

I am new to programming in functional languages. I am attempting to implement the F# collect for list.
let rec collect func list =
match list with
| [] -> []
| hd::tl -> let tlResult = collect func tl
func hd::tlResult;;
collect (fun x -> [for i in 1..3 -> x * i]) [1;2;3];;
should print:
val it : int list = [1; 2; 3; 2; 4; 6; 3; 6; 9]
but I got:
val it : int list = [[1; 2; 3;], [2; 4; 6;], [3; 6; 9]]
Here's a tail recursive collect that won't stack overflow for large lists.
let collect f xs =
let rec prepend res xs = function
| [] -> loop res xs
| y::ys -> prepend (y::res) xs ys
and loop res = function
| [] -> List.rev res
| x::xs -> prepend res xs (f x)
loop [] xs
A simpler version, that's somewhat cheating, is:
let collect (f: _ -> list<_>) (xs: list<_>) = [ for x in xs do yield! f x ]
The collect function is tricky to implement efficiently in the functional style, but you can quite easily implement it using the # operator that concatenates lists:
let rec collect f input =
match input with
| [] -> []
| x::xs -> (f x) # (collect f xs)

List.rev and empty list []

I am not really understand about the function (parse_list) at
None -> List.rev is and None -> []
let try_parse parse x = try Some (parse x) with Error _ -> None;;
let parse_list parse =
let rec aux is = function
| [] -> List.rev is, []
| (hd :: tl) as xs ->
match try_parse parse hd with
| Some i -> aux (i::is) tl
| None -> List.rev is, xs
in aux [];;
and
let parse_list parse =
let rec aux is = function
| [] -> List.rev is, []
| (hd :: tl) as xs ->
match try_parse parse hd with
| Some i -> aux (i::is) tl
| None -> [], xs
in aux [];;
Are they different? could you please give me an example if they are different? Thank you very much
Yes, they are different.
In the first one, when the parse function will fail, the function parse_list will return a partial list of "parsed" expression (List.rev is).
In the second one, when the parse function will fail, you'll get an empty list from parse_list ([]).
Look this example with a parse function which will keep only integers lesser than 3:
let test_parse x = if x < 3 then x else raise Error "error";;
With the first implementation you'll get:
# parse_list test_parse [1; 2; 3; 4; 5];;
- : int list * int list = ([1; 2], [3; 4; 5])
wit the second one, you'll get:
# parse_list test_parse [1; 2; 3; 4; 5];;
- : int list * int list = ([], [3; 4; 5])