简体   繁体   中英

Type-error OCaml

I'm actually a french student in computer science and I'm following a course called Advanced Programming. For the purpose of the course i need to develop a game in OCaml...blablabla... But I'm facing an issue that i can't figured out alone.

As you can see below, I created a function called l_exists (that I consider is an extension to List.exists with the behavior I expect). That function return a list of elements which agreed with the predicat.

The problem is "meme_pos". I had a type-error but I don't understand why because the type objet is also a type of position. So, if someone can show me what's wrong and how to avoid it. I will be very satisfied.

By the way, sorry for my english. I did my best :/

type position = { i : int; j : int }

type objet =
  | Robot of position
  | Debris of position

let l_exists p li arg_s =
  let rec aux l acc = match l with
    |[] -> acc
    |x::xs -> aux xs (if(p arg_s x) then x::acc else acc)
  in aux li []

val l_exists : ('a -> 'b -> bool) -> 'b list -> 'a -> 'b list = <fun>

let meme_pos pos (objetl:objet list) =
  let p_pos_egale (pos1:position) (pos2:position) =
    if(pos1=pos2) then true else false
  in l_exists p_pos_egale objetl pos

Error: This expression has type objet list but an expression was expected of type position list.
Type objet is not compatible with type position.
Expression : in l_exists p_pos_egale objetl pos
val l_exists : ('a -> 'b -> bool) -> 'b list -> 'a -> 'b list = <fun

You declare p_pos_egale :

let p_pos_egale (pos1:position) (pos2:position) = pos1=pos2

and after that you write

l_exists p_pos_egale objetl pos

Let's apply l_exists to p_pos_egale :

# l_exists p_pos_egale;;
- : position list -> position -> position list = <fun>

If you substitute your p_pos_egale to l_exists you will see that 'a becomes the same as 'b , ie position . OCaml decides that objetl should be a list of positions but you specified type objel list manually in meme_pos definition. So, this error appears.

Very likely you need to rewrite your p_pos_egale definition. It should have type objel -> position -> bool .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM