我需要“解压缩”一个元组列表,即使我尝试使用unzip
函数,它也没有按照我想要的方式执行。事实上,据我所知,unzip
函数会返回一个列表元组,但我想要的是这个。
给出一个像这样的元组列表:
L1 = [(("s0","l0"),("l0","s1")),(("s1","l1"),("l1","s2"))]
类型:
(string*string)*(string*string) list
该函数应该返回由解压缩元组组成的单个列表:
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;
并且我认为它可以工作但是当我运行该功能时系统崩溃。
答案 0 :(得分:1)
我不完全确定你发布的功能是什么,但它几乎肯定不会为你解压缩2元组的列表。它似乎期望3元组,并启动一些解引用/连接。你是怎么找到它的?
如果你想要一个带有2元组列表并返回其元素列表的函数,你可以这样做
fun peel lst =
let fun recur [] acc = List.rev acc
| recur ((a, b)::rest) acc =
recur rest (b::a::acc)
in
recur lst []
end
即,遍历列表,收集每个元组的两个元素,并在结束时返回累加器的反向。
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
-
由于其定义的方式,它具有(可能不必要的奖励)它可以类似地处理任何2元组的列表。
- peel (peel [(("s0","l0"),("l0","s1")),(("s1","l1"),("l1","s2"))]) ;;
val it = ["s0","l0","l0","s1","s1","l1","l1","s2"] : string list
-