let rec some_none list =
match list with
| [] -> list
| hd::tl ->
if hd = 0 then
[None] # some_none tl
else
[Some hd] # some_none tl;;
When I run this program it returns
Error: This expression has type int list but an expression was expected of type
'a option list
Type int is not compatible with type 'a option
How can I make it so that I am able to change a regular a' list to a' option list?
These two lines
match list with
| [] -> list
imply that the list returned by some_none has the same type as its argument.
Changing that line to
| [] -> []
solves the issue, since the left-hand and right-hand side are now unrelated.
A more subtle way (and not really useful here) is to use the as construct,
| [] as x -> x
because ... as x construct captures the type of the pattern rather than the type of the scrutinee (here list). However, this construction is mostly useful with polymorphic variants.
Also notice that your function some_none change neither the length of the list nor the order of the elements of the list. This means that it can be written as a map:
let some_none = List.map (fun elt -> ... )
Adding to what octachron has already said, there's a few style and performance issues with your code too.
First, it's unnecessary to create a new list in order to concatenate it using # when :: exists to prepend a single element to a list:
let rec some_none list =
match list with
| [] -> []
| hd::tl ->
if hd = 0 then
None :: some_none tl
else
Some hd :: some_none tl
Second, you can match on literal patterns directly instead of using comparison in an if expression within the branch:
let rec some_none list =
match list with
| [] -> []
| 0::tl -> None :: some_none tl
| hd::tl -> Some hd :: some_none tl
Third, you can use function to match directly on the last function argument:
let rec some_none = function
| [] -> []
| 0::tl -> None :: some_none tl
| hd::tl -> Some hd :: some_none tl
And fourth, you can use List.map to transform elements individually:
let some_none =
List.map (function 0 -> None | x -> Some x)
And now you have a function that is suddenly much easier to read and understand fully.
Related
I created a function that insert one element in a list.
The insertion will happens when the element i is equal to k.
The list is a list of (int * string) list , like [(1,"hi")...]
The idea is to create a new list where for each iteration hd is append at the beginning.
When i is found then k is inserted and the function stops.
Here the code :
let rec insert k v list_ =
let rec support k v list _
match list_ with
| (i,value) when i = k -> (k,v) :: tl
| hd :: [] -> hd
| hd :: tl -> hd :: support k v tl in
let inserted = support k v list_
let () =
let k = [ (1,"ciao");(2,"Hola");(3,"Salut") ] in
insert 2 "Aufwidersen" k
I think all is fine but the compiler said :
5 | | hd :: [] -> hd
Error: This pattern matches values of type 'a list
but a pattern was expected which matches values of type 'b * 'c`
And I don't understand why, I think all is ok.
The problem is this part:
match list_ with
| (i,value) -> ...
When you write this, Ocaml infers that list_ has to be a tuple, which is a type error because it is actually a list of tuples.
I didn't understand exactly what you want the insert function but the typical pattern is to have two cases, one for the empty list and one for the non-empty list. I personally prefer using if-then-else instead of pattern guards but if you want to use pattern guards that should also work. Either way, you certainly want to cover the case of the empty list.
match list_ with
| [] -> (* ... *)
| (i,value)::tl ->
if i = k then
(* ... *)
else
(* ... *)
My data is ordered like this:
([(x1,y1,z1);(x2,y2,z2);(x3,y3,z3);........;(xn,yn,zn)], e:int)
Example: I try to create a list [x1;x2;x3;....;xn;e] where a value is found only once.
I began the following code but I encounter an issue with type.
let rec verifie_doublons_liste i liste = match liste with
| [] -> false
| head::tail -> i = head || verifie_doublons_liste i tail
let rec existence_doublon liste = match liste with
| [] -> false
| head::tail -> (verifie_doublons_liste head tail) ||
existence_doublon tail
let premier_du_triplet (x,y,z) = x
let deuxieme_du_triplet (x,y,z) = y
let troisieme_du_triplet (x,y,z) = z
let rec extract_donnees l = match l with
| [] -> []
| (x,y,z)::r -> (extract_donnees r)##(x::z::[])
let arrange donnees = match donnees with
| [],i -> i::[]
| (x,y,z)::[],i -> x::z::i::[]
| (x,y,z)::r,i -> (extract_donnees r)##(x::z::i::[])
Basically, you want to extract first elements in a list of tuples, and add the e elemnent at the end.
The easiest way is to use a List.map to extract the first elements
List.map premier_du_triplet
is a function that will take a list of 3-tuples and extract the first element of each.
then you can add the e element at the end using the "#" operator.
The more efficient and informative way would be to directly write a recursive function, say f that does just what you want.
When writing a recursive function, you need to ask yourself two things
what does it do in the simplest case (here, what does f [] do ?)
when you have a list in format head::tail, and you can already use f on the tail, what should you do to head and tail to obtain (f (head::tail)) ?
With this information, you should be able to write a recursive function that does what you want using pattern matching
here the simplest case is
| [] -> [e]
(you just add e at the end)
and the general case is
| h::t -> (premier_de_triplet h)::(f t)
let rec (l:int list) f int list =
match l with
| [] -> []
| hd::tl -> 2+tl
I want to know is hd the first element and then tl is the second element because when i do this I keep getting an error, if tl is not the second element how would i access the second element an in depth explanation of hd::tl would be highly appreciated thank you
No tl is not the second element, it is the rest of the list and it has type 'a list. Here hd and tl are just variable names that you choose to bind to the first element of a list, and to the rest of the list (i.e., to a list that contains all elements except the first one). You can choose other names, e.g., fst::rest. Getting the second element, in that case would be as easy as fst::snd::rest (or x::y::rest - again the name doesn't matter).
What you're trying to use is called pattern matching. It is a feature of some languages, that provides a mechanism to easily deconstruct compound data structures. The idea is that if you're deconstructing data structures the same way as you're constructing them, e.g,
let xs = [1;2;3;4]
and here is the deconstructing
let [x1;x2;x3;x4] = xs
In fact, [x;y;...;z] is a syntactic sugar for a more basic syntax x :: y:: ... :: z :: [], so another way to construct the [1;2;3;4] list is to use the following construct: 1::2::3::4::[]. The same works in the opposite direction, e.g.,
let x1::x2::x3::x4::[] = xs
Now we are ready to the next step, what if the structure on the right doesn't match the structure on the left, e.g.,
let [x;y;z] = [1;2]
or
let x::y::z::[] = 1::2::[]
In that case, the matching will fail. In our case in runtime. To prevent this, and to allow programmers to handle all possible configuration of their data structures OCaml provides the match construct in which you specify multiple variants of the value structure, and the first one that matches is chosen, e.g.,
let orcish_length xs = match xs with
| [] -> 0
| x :: [] -> 1
| x :: y :: [] -> 2
| x :: y :: z :: [] -> 3
The function above anticipates only lists that have up to three elements (because Orcs can't count beyond three). But we can. For this we will use the following feature -- if the last element of the list pattern is not [] (that is matches only and only with the empty list, and designates the end-of-list), but anything else (i.e., a variable), then this variable will be bound to all elements, e.g.,
let rec elvish_length xs = match xs with
| [] -> 0
| x :: [] -> 1
| x :: y :: [] -> 2
| x :: y :: z :: [] -> 3
| x :: y :: z :: leftovers -> 3 + elvish_length leftovers
So now, we anticipate all possible list patterns. However, the function is now overcomplicated (because Elves are complicating). Now, let's finally derive a normal, human readable, length function,
let rec length xs = match xs with
| [] -> 0
| x :: xs -> 1 + length xs
As an exercise, try to prove to yourself that this function anticipates all possible lists.
:: is read cons and is an infix version of List.cons. In a functional language like Ocaml, list is a linked list where i.e.[e1; e2; e3; e4] can be reduced to something like this:
cons(::)
/ \
e1 cons(::)
/ \
e2 cons(::)
/ \
e3 cons(::)
/ \
e4 [ ]
Basically, any list can be reduced to a tree of recursive cons expressions, which makes recursion so useful in Ocaml or similar functional languages. At each level, you can reduce a list to its head and its tail, where tail is the list minus its head and can be reduced further until last :: []. So with the above example, you can recursively reduce the list until you find the last element by pattern-matching:
let find_last li =
match li with
| [] -> None (* no element *)
| [last] -> Some last (* found last *)
| head :: tail -> find_last tail (* keep finding *)
;;
Note that [last] can be replaced with last::[] and head::tail with List.cons head tail. What is important is at any point a list can always be reduced to head :: tail, where head is the first element and tail is the list without head.
Pattern-matching is useful in matching the "shape" or state of the reducing list.
I'm trying to implement a RLE decoder for a game, and it works, but I'd like to shrink the code a bit, but I can't figure out how to put List.append and the repeat and rleExpand calls on one line
The signature of List.append is List.append : 'T list -> 'T list -> 'T list, so obviously I cannot just do
List.append(repeat(pattern,count), rleExpand(tail,rleTag)) - but would like to know how to do that. I also can use the # operator - maybe that's the most readable one. But how do I use List.append if my lists are created by a function application like in the listing below?
let rec repeat(item,count) =
match count with
| 0 -> []
| n -> item :: repeat(item,n-1)
let rec rleExpand(packed, rleTag: int) =
match packed with
| [] -> []
| tag :: count :: pattern :: tail when tag = rleTag ->
let repeated = repeat(pattern,count)
let rest = rleExpand(tail,rleTag)
List.append repeated rest
| head :: tail -> head :: rleExpand(tail,rleTag)
I would probably write:
repeat(pattern,count) # rleExpand(tail,rleTag)
But you can also write
List.append (repeat(pattern,count)) (rleExpand(tail,rleTag))
You cannot use List.append(repeat(pattern,count), rleExpand(tail,rleTag)) as you originally suggested because List.append takes curried (rather than tupled) arguments.
Does something like this work?
let repeat(item, count) = [for i in 1 .. count -> item]
let rec rleExpand(packed, rleTag: int) =
match packed with
| [] -> []
| tag :: count :: pattern :: tail when tag = rleTag ->
List.collect id [repeat(pattern,count); rleExpand(tail,rleTag)]
| head :: tail -> head :: rleExpand(tail,rleTag)
It's also more commonplace to use make functions curryable by not using tuples as parameters.
Here is my original code.
let rec reverse l =
match l with
| [] -> []
| (h::t) -> (reverse t) :: h
The cons :: operator takes an element as left-hand argument and a list as right-hand argument. Here, you do the opposite which does not work.
The right way to add an element at the element at the end of a list is to use list concatenation:
let rec reverse l =
match l with
| [] -> []
| h :: t -> (reverse t) # [h]
That code is not optimal though, and you may want to make it tail recursive.