2013-10-06 56 views
0

我想知道如何返回另一個列表中特定值出現的索引列表。 即 索引(1,[1,2,1,1,2,2,1]); val it = [1,3,4,7] int list標準ML - 返回列表中給定值出現的索引

我想弄清楚列表是如何工作的,並試圖在遞歸方面做得更好,所以我不想使用List.nth(或任何庫函數),我不想進入模式匹配安靜。

這是我迄今爲止

fun index(x, L) = 
if null L then 0 
else if x=hd(L) then 
    1 
else 
    1 + index(x,tl L); 

fun inde(x, L) = 
if null L then [] 
else if x=hd(L) then 
    index(x, tl L) :: inde(x, tl L) 
else 
    inde(x, tl L); 

index(4, [4,2,1,3,1,1]); 

inde(1,[1,2,1,1,2,2,1]); 

這讓我有點像[2,1,3,0]。我想我只是很難正確地增加事物來獲得索引。索引函數本身可以正常工作。

回答

1

相反,你也可以讓兩個超過列表:首先添加一個索引到列表中的每個元素,和第二虎視眈眈右元素的索引:

fun addIndex (xs, i) = 
    if null xs then [] 
    else (hd xs, i) :: addIndex(tl xs, i+1) 

fun fst (x,y) = x 
fun snd (x,y) = y 
fun indexi(n, xs) = 
    if fst(hd xs) = n then ... :: indexi(n, tl xs) 
    else indexi(n, tl xs) 

(我離開了的indexi一部分) 其中addIndex([10,20,30],0)給你[(10,0),(20,1),(30,2)]。現在你可以使用addIndexindexi實現你原來index功能:

fun index(n, xs) = indexi(n, addIndex(xs, 0)) 

當你得到那個工作,你可以嘗試合併addIndexindexi成一個函數,它把兩種。

但是,你真的想與模式匹配寫這篇文章的,例如參見addIndex書面使用模式:

fun addIndex ([], _) = [] 
    | addIndex (x::xs, i) = (x,i) :: addIndex(xs, i+1) 
+0

這是有道理的,但我找不出如何做的是如何將一個飼料JUST列表L到indexi函數,然後得到相同的結果?我無法向indexi提供元組(這是我能找到的唯一方法) – Nexion

0

如果你做索引(1,[2]),它給出1,這是不正確的。當列表爲空時,它會給你零。在這樣的功能中,你可能會想使用SOME/NONE功能。