0

I have this:

val a = ((1,2),(1,2,1),(1,2,3),5,(4,5,6));

I need a function that returns few "x" is in this tuple...

Example: Few "5" is in the tuple:

funMagic (a,5);

Must return 2

Help!

Neutron25
  • 11
  • 1
  • Have you even tried to solve this yourself? If so, please share your attempt & what problem(s) it has. – Scott Hunter Oct 13 '16 at 01:48
  • try to access as if it were a list (a :: b) a = first tuple, b = other tuples. but it only works with 2-tuples tuple... – Neutron25 Oct 13 '16 at 01:54
  • 1
    It seems like `funMagic` is supposed to count the number of times that a given int appears. If so, you could write a function which will flatten this tuple of tuples into a list of 12 ints (hint: a 1-line definition), and then feed the result to a function (which you will also have to write) which counts the number of occurrences of an element in a list. That way, you can separate the logic of dealing with the tuples from the logic of counting. – John Coleman Oct 13 '16 at 02:45

2 Answers2

3

There may be some mistake in your question. In SML (as well as other major statically typed functional programming languages such as OCaml and Haskell), tuples have different types depending on the number (and types) of the elements. For example, your tuple a has the following type:

(int * int) * (int * int * int) * (int * int * int) * int * (int * int * int)

As a result, your function funMagic can only take a quintuple (a tuple with 5 elements) whose elements are themselves tuples with 2, 3, 3, 1, and 3 elements, respectively (in fact, there is no "tuple with 1 element" in SML; assume that it is equivalent to the element itself), at least unless you adopt some type encoding trick. Do you perhaps mean lists (such as [[1,2],[1,2,1],[1,2,3],[5],[4,5,6]]) rather than tuples?

FPstudent
  • 831
  • 5
  • 9
  • Your answer is more of a comment than an answer and normally I object to such answers, but you have done a good job in explaining some of the issues that the question raises. – John Coleman Oct 13 '16 at 10:14
0

The function would look similar to this one. I suggest, your main problem was not to create the function, but to access a position in a tuple of tuples.

funmag: (int*int)*int -> int
funMag (p:(int*int)*int) = #2(#1 p)

This function will "look up" the first position of the big tuple and then jump to the 2nd position of the small tuple. So for example our tuple is ((5,7),3) then our function will return 7

Max K
  • 171
  • 12