有個需求,比如在一個列表中,取出一個元素的位置,如果出現重復都取出。例如:List = [2,3,10,324,88,29,12],可以求大於某個值的位置,也可以取某個值的位置。
廢話少說,直接上代碼:
%%測試用例 enter() -> A = [true,false,true,false,true,false,true,true], %A = [10,11,20,3,9.2,8.23,10.4,9.2], N = lists:foldr(fun(X,Y) -> case lists:nth(X,A) == true of true -> [X|Y]; false -> Y end end, [],lists:seq(1,length(A) )), io:format("N......123...~p~n",[N]), N.
在上述例子中,是找true在列表A中的位置。運行結果如下:
即找到對應的true在列表A中的位置.
或由遞歸遍歷:
get_obj_index(Obj,List) -> get_Obj_index(Obj, List, 1). get_Obj_index(Obj, [First | Other],Index) -> case First =:= Obj of true -> Index; false -> get_Obj_index(Obj, Other, Index+1) end; get_Obj_index(_Obj, [],_Index) -> undefind.