SML - 在一个列表中解压缩元组

SML - Unzip tuples in one list

我需要 "unzip" 一个元组列表,尽管我尝试使用 unzip 函数,但它没有执行我想要的操作。事实上,据我了解 unzip 函数 return 是一个列表元组,但我想要的是这个。

给出这样的元组列表:

L1 = [(("s0","l0"),("l0","s1")),(("s1","l1"),("l1","s2"))]

类型:

(string*string)*(string*string) list

该函数应该 return 我一个由解压缩的元组组成的列表:

L2 = [("s0","l0"),("l0","s1"),("s1","l1"),("l1","s2")]

类型:

(string*string) list

我找到的唯一解决方案是:

fun f(h as (x,y,z),nil) =  [(x,x^y^z)]@[(x^y^z,z)]
|f (h as (x,y,z),t::rest) = 
    let val i = ref 0
        in if !i=0 then (i := !i+1; (x,x^y^z)::f(h,t::rest)) else (i := !i-1;(x^y^z,z)::f(t,rest)) end;

我认为它可以工作,但是当我 运行 该功能时系统崩溃了。

我不完全确定您发布的函数有什么作用,但几乎可以肯定它不会为您解压缩二元组列表。它似乎期望 3 元组,并执行一些 de-referencing/concatenation 启动。你是怎么找到的?

如果您想要一个接受二元组列表和 return 元素列表的函数,您可以这样做

fun peel lst =
    let fun recur [] acc = List.rev acc
      | recur ((a, b)::rest) acc = 
        recur rest (b::a::acc)
    in 
    recur lst []
    end

也就是说,遍历列表,收集每个元组的两个元素,return当你到达末尾时,与你的累加器相反。

Standard ML of New Jersey v110.76 [built: Thu Feb 19 00:37:13 2015]
- fun peel lst =
    let fun recur [] acc = List.rev acc
      | recur ((a, b)::rest) acc = 
        recur rest (b::a::acc)
    in 
    recur lst []
    end ;;
= = = = = = [autoloading]
[library $SMLNJ-BASIS/basis.cm is stable]
[autoloading done]
val peel = fn : ('a * 'a) list -> 'a list
- peel [(("s0","l0"),("l0","s1")),(("s1","l1"),("l1","s2"))] ;;
val it = [("s0","l0"),("l0","s1"),("s1","l1"),("l1","s2")]
  : (string * string) list
- 

由于其定义方式,它具有(可能是不必要的好处)可以类似地处理任何二元组列表。

- peel (peel [(("s0","l0"),("l0","s1")),(("s1","l1"),("l1","s2"))]) ;;
val it = ["s0","l0","l0","s1","s1","l1","l1","s2"] : string list
-