-2

What could be the possible function foo, which has a type

’a * ’a -> int

in ML. i.e. a function which has the following type of the output

Rook
  • 5,734
  • 3
  • 34
  • 43
  • `fun (x, y) -> if x = y then 1 else 2` has type `'a * 'a -> int` – newacct Oct 21 '13 at 07:08
  • 1
    @newacct, that depends on which ML the OP is talking about. Your example is in OCaml, but the equivalent code in Standard ML will not have the requested type. – Andreas Rossberg Oct 21 '13 at 07:38
  • Hello, Yes I do know the basic syntax of ML. And the question is related to the type inference and the output must be of the form α × α → int – user2803957 Oct 21 '13 at 23:22
  • @AndreasRossberg could you please help me with it. I have to run that in UNIX command prompt. – user2803957 Oct 23 '13 at 04:03

1 Answers1

2

This seems to be homework, so I give you a partial solution and some hints only. The type you want is a 'a * 'a -> int, so the skeleton of a suitable function could be something like this (I assume you are using Standard ML):

fun foo(x, y) = ???

The ??? needs to meet two requirements: it must contain an expression that forces x and y to have the same type, and it must return an integer. The latter shouldn't be hard. For the former, there are many possibilities in SML, e.g., putting them in the same list, or returning them from the branches of the same if or case or handle.

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72
  • Perfect answer. Out of interest, there's once thing I was wondering. You said "there are many possibilities" for constraining the types of `x` and `y`. But for the life of me, aside from passing them to the same function, or putting them in the same data structure, I can't think of another. Can you? – Nick Barnes Oct 23 '13 at 15:11
  • @NickBarnes, I'm slightly confused what you are asking, since I seem to list all the ones I could think of in the answer already? – Andreas Rossberg Oct 23 '13 at 17:06
  • It wasn't clear whether your list was meant to be exhaustive. Just curious to see if you had any more, since there are large parts of the language which I've pretty much forgotten (mutable types, loops, functors, even exception handling...). Now that I think about it, while `if` and `case` are just functions, it seems that `handle` falls into a different category. – Nick Barnes Oct 24 '13 at 01:25
  • @NickBarnes, ah ok, no, it's not exhaustive, there probably are other ways. Actually, references would be another, somewhat different example from the data structure camp. You can also use exception and datatype constructors in various ways, although that arguably amounts to using indirect type annotations. – Andreas Rossberg Oct 24 '13 at 07:03