简体   繁体   中英

processing tuples in SML

I have an assignment where I need to take a tuple and return another tuple, of the same size, with certain elements changed. The problem is I don't know how to process a tuple of an undefined size. The function needs to be able to process tuples of any size. My idea was to make the tuple into a list that i could process much more easily, by making a recursive helper function to take element #1 of the tuple and cons it to a call to the same function which would give element #2 consed onto the recursion again until there are no elements left, but this just gives an error when i get to #n+1 where n is the total number of items in the tuple. Am I going about this the wrong way? is there a way to find the size of a tuple? is there a way to handle this error? I know about exception handling, but I'm not sure how to apply it to his case, if even possible.

the question is create a function named subst, such that subst (e',x) e = [e'/x]e ie the function subst will replace any free occurrence of the variable x in the expression e' by the expression e. Add the appropriate case for tuples.

The function needs to be able to process tuples of any size.

This cannot be done. Tuples of different sizes are completely different and unrelated types; there is no type of function that is polymorphic enough to be both 'a * 'b -> ... and 'a * 'b * 'c -> ... , unless it's simply of type 'a -> ... (ie, it accepts any argument at all, with no special understanding of tuples).

(The built-in notations # 1 , # 2 , etc. are overloaded functions that work for any tuple type, but this is magic that you can't duplicate. You can't even write something like val f = # 1 without giving the compiler enough information to infer f 's exact type; you'd have to write eg val f : 'a * 'b -> 'a = # 1 to specify that f returns the first field of 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