I am trying to write a function which can either return an int or a string, based on the result of a call to a function baz.
type 'a foo = OK of 'a | Error of string
let bar (e) : int foo =
match baz e with
| OK (_) -> 1
| Error s -> s
However, I get this error message when compiling:
Error: This expression has type int but an expression was expected of type
int foo
Command exited with code 2.
What exactly am I doing wrong here?
EDIT: Here's the actual snippet of code I'm dealing with:
type 'a error = | OK of 'a | Error of string
type typing_judgement = subst*expr*texpr
let rec infer' (e:expr) (n:int): (int*typing_judgement) error =
match e with
| _ -> failwith "infer': undefined"
let infer_type (AProg e) =
match infer' e 0 with
| OK (_, tj) -> string_of_typing_judgement tj
| Error s -> "Error! "^ s
The end goal here is a type inference engine, so as I can tell infer_type will be given an expression, which will be passed to infer' (which I will have to implement). I've never worked with Ocaml before and I'm just trying to get this to compile before I even attempt to implement these functions.
int fooas the return type, when it's actually the argument type. There's really not much that makes sense about the code you've written. Perhaps if you provide a bit more context it would be possible to understand what you're actually trying to do. - glennslbaris supposed to representinfer_type, the latter returns astringin each branch, so no problem there. - glennslstring_of_typing_judgementis undefined, so I took it out temporarily. You're saying taking that out could be causing the issue, since when it's in both branches return a string? I don't really understand how pattern matching works, is it thatstring_of_typing_judgementtakes on the value of whatever the wildcard matched? And if so, then it will resolve to a string applied to a typing_judgement, which doesn't make sense to me. (Again, sorry for the ignorant questions, I have no experience with Ocaml whatsoever). - Christian Bouwensestring_of_typing_judgementis used as a function here, being given atyping_judgement(tj). And by the name of it I'd say it's supposed to transform thetyping_judgementinto astring, which happens to work out well since the other branch returns a string as well. If the function is undefined, I guess that means you're supposed to implement it yourself. You also might want to pick up a book on the language, because these are pretty basic language concepts and you only seem to confuse yourself more by making flawed assumptions about them. - glennsl