在sml中压缩超过2个列表

时间:2013-12-04 21:09:16

标签: sml

我的功能中有尾巴问题。我想摆脱尾巴,但我想不出办法。如果有人可以协助我找到出路,我会很高兴。

fun Rollists (x::nil) = [x]
  | Rollists (xs) =(map hd xs)::Rollists( map tl xs); 

这个函数,应该从给定列表列表中输出每个列表中的元素,更大版本的ListPair.zip

1 个答案:

答案 0 :(得分:2)

根据第一个列表从列表列表中生成对:

fun generateTuples (lol) =
    let
    (*  Treat the ListOfLists as a database
        table, with the first
        list being a key value column *)
    val keys  = hd(lol)

    (*  and the remaining columns being
        additional fields in its tuple *)
    val records  = tl(lol)

    (*  Pairs the key with each column
        in its record *)
    fun formPairs (aKey,listOfRecords) =
        if null listOfRecords
        then []
        else [aKey,hd(hd listOfRecords)]::
         (formPairs(aKey,tl(listOfRecords)))

    (*  Pops a row's data fields from the record *)
    fun chopLists (listOfRecords)=
        if null listOfRecords
        then []
        else tl(hd(listOfRecords))::
         (chopLists(tl(listOfRecords)))
    in
    (*  Pass the first key value to formPairs
        along with all the records. Then pop
        the first row off the database and call
        generateTuples on the remain *)
    if null keys 
    then []
    else generateTuples(tl(keys)::(chopLists(records)))
         @ formPairs(hd(keys),records)      
    end

示例:

val list1 = [0,1,2,3,4]
val list2 = [55,66,77,88,99]
val list3 = [10,11,12,13,14]
val list4 = [555,666,777,888,999]
val lols = [list1,list2,list3,list4]

- generateTuples(lols);
val it =
  [[4,99],[4,14],[4,999],[3,88],[3,13],[3,888],[2,77],[2,12],[2,777],[1,66],
   [1,11],[1,666],...] : int list list