Search code examples
stringlistrecursionsml

SML - Recursive function for list string


I need your help! I'm trying to create a function that takes as input two elements of type

    (string*string*string) list 

and

    (string*string) list

and return an element of type

    (string*string) list 

manipulating in a specific way. I need something like:

    returnString(([("s0","l0","s1"),("s1","l1","s0")]),([("s0","phi1"),("l0","chi1"),("l1","chi2"),("s1","phi2")])); 

the function that takes these inputs should return me:

    val it = [(("s0l0s1","chi1"),("s1l1s0","chi2"))]

which should be: If the second string of the first input element

    (string*string*string) 

corresponds to the first string of the second input element

    (string*string) 

then i would put the elements i need in the list otherwise i continue to check.

I tried a lot of way of doing that...with recursive functions, with the map functions...but I'm a kind new to this language and I couldn't find a way since sml is not easy to handle with loop.

I would really appreciate if you help me or even if you have some hints to propose.

Thanks a lot everybody!


Solution

  • Let me know if the explanations in the code make sense.

    fun example (xss, yss) =
      case (xss, yss) of
        (* If the 1st list is empty, then the result is an empty list. *)
        ([], _) => []
        (* If the 2nd list is empty, then the result is also an empty list. *)
      | (_, []) => []
        (* Otherwise, we decompose the tuples in the two lists *)
      | ((a, b, c) :: xs, (x, y) :: ys) =>
          (* verify that our condition holds *)
          if b = x then
            (* in which case we have a solution and recurse with the rest *)
            (a ^ b ^ c, y) :: example (xs, ys)
          else
            (* otherwise, we recurse with the first list intact, but skip the *)
            (* current element in the second list. *)
            example (xss, ys)
    

    Also, check out this answer of mine, to understand how functions get called in Standard ML.