Combined Function in SML

Hey, I am very new to SML and programming all together, I want to write a function that combines into lists, so [x1, x2, x3, x4, ...] = [(x1, x2), (x3, x4) , ...] Any tips or help for me in the right direction is greatly appreciated.

+3
source share
2 answers

Studying the problem, it becomes obvious that we will probably want to process the input with two elements at a time.

So, let's see what we want to do with each pair: if x1 and x2 are the elements that we are currently viewing, we want to put the pair (x1, x2)in the list we create. If xs- a list of elements that appear after x1and x2, we want the pair to be (x1, x2)followed by the result of the "union" xs. Thus, we can write our combination function as:

fun combineWithin (x1::x2::xs) = (x1, x2)::(combineWithin xs)

However, this definition is not yet complete. We look only at the case when it xshas at least two elements. Therefore, we need to ask ourselves what we want to do in the other two cases.

For an empty list, this is easy: the result of combining an empty list is an empty list.

, (, , ). : , combineWithin [1,2,3] [(1,2)] [(1,2), (3,3)] .

, , :

fun combineWithin (x1::x2::xs) = (x1, x2)::(combineWithin xs)
  | combineWithin _ = []
+3
let rec pairs = function
| [] -> []
| [x] -> []
| x1::x2::rest -> (x1, x2)::(pairs rest)
-1

Source: https://habr.com/ru/post/1766363/


All Articles