简体   繁体   中英

OCaml pattern matching type error

I have this segment of a function:

and interpret_read (id:string) (mem:memory)
               (inp:string list) (outp:string list)
: bool * memory * string list * string list =
  match inp with
  | [] -> raise (Failure "unexpected end of input")
  | head :: tail -> (true, (append mem (id, int_of_string head)), tail, outp)

The memory type is defined as follows:

type memory = (string * int) list;;

When I try to #use the source code I get the following error:

Error: This expression has type 'a * 'b
but an expression was epected of type (string * int) list

I'm still new to Ocaml so as I understand it 'a and 'b are generic types and they need to be defined as string and int before they can be appended to mem. I feel like that understanding isn't completely accurate because if that were the case id should already be defined as a string and int_of_string head should be an int. Can anyone help me clear up my confusion?

EDIT: I have changed the function to the following:

and interpret_read (id:string) (mem:memory)
               (inp:string list) (outp:string list)
: bool * memory * string list * string list =
  match inp with
  | [] -> raise (Failure "unexpected end of input")
  | head :: tail -> (true, mem :: (id, int_of_string head), tail, outp)

And I receive the following error:

This expression has type memory = (string * int) list 
but an expression was expected of type string * int

This doesn't make sense to me because it's supposed to be of type memory.

If I change the function to the following:

    and interpret_read (id:string) (mem:memory)
               (inp:string list) (outp:string list)
: bool * memory * string list * string list =
  match inp with
  | [] -> raise (Failure "unexpected end of input")
  | head :: tail -> (true, (id, int_of_string head), tail, outp)

Then I get the following error:

This expression has type 'a * 'b 
but an expression was expected of type memory = (string * int) list

Which is what the the expression's type just was! There's definitely something I'm missing here, but I can't figure it out.

You don't give a definition for append . If I assume this is List.append , its type is 'a list -> 'a list -> 'a list . Ie, it takes two lists and returns a list. But you're passing a list and a single element (a pair).

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