0

我正在尝试编写一个谓词来根据公共索引在列表中添加元素。我到目前为止所做的当然不值得展示...... =(

预期的行为将类似于:

List = [ ]

add_to_list( List, Index1, Param1, Value1 )
List = [
    [ Index1, [ Param1, Value1 ] ]
]

add_to_list( List, Index1, Param2, Value2 )
List = [
    [ Index1, [ Param1, Value1 ], [ Param2, Value2 ] ]
]

add_to_list( List, Index2, Param3, Value3 )
List = [
    [ Index1, [ Param1, Value1 ], [ Param2, Value2 ] ],
    [ Index2, [ Param3, Value3 ] ]
]
4

2 回答 2

2

好吧,这种行为是不可能的(除非我们用类似的东西将 prolog 破解成碎片setarg/3)。(有关更多详细信息,请检查破坏性与单一分配

一个非常相似的行为是:

List0 = [ ]

add_to_list( List0, Index1, Param1, Value1, List1)
List1 = [
    [ Index1, [ Param1, Value1 ] ]
]

add_to_list( List1, Index1, Param2, Value2, List2)
List2 = [
    [ Index1, [ Param1, Value1 ], [ Param2, Value2 ] ]
]

add_to_list( List2, Index2, Param3, Value3, List3)
List3 = [
    [ Index1, [ Param1, Value1 ], [ Param2, Value2 ] ],
    [ Index2, [ Param3, Value3 ] ]
]

当然,因为我们不做单独的东西,Param我们Value可以将它们作为一个变量传递 add_to_list(List1, Index, Val, List2)Val = [Param, Value]

一个简单的实现是:

add_to_list(L1, I, Val, L2):- member([I,Rest],L1) -> ( append(Val,Rest,FRest), select([I,Rest], L1, [I,Frest], L2)); 追加([[I,Val]],L1)。

但这很慢;将新元素添加到列表的头部要快得多(也更容易!)。

最后,根据我的经验,最好使用关联列表,它非常快并且可以轻松地为您的问题建模

于 2012-10-12T21:56:39.790 回答
1

我通过这样做得到了它:

add_to_list( [ ], Param, Val, Val2, [ [ Param, [ [ Val, Val2 ] ] ] ] ).
add_to_list( L, Param, Val, Val2, LNew ) :-
    member( [ Param, Vals ], L ) ->
    (   select( [ Param, Vals ], L, L2 ),
        not( member( [ Val, Val2 ], Vals ) ) ->
        (   append( Vals, [ [ Val, Val2 ] ], Vals2 ),
            append( [ [ Param, Vals2 ] ], L2, LNew )
        );  append( L, L2, LNew )
    );  append( L, [ [ Param, [ Val, Val2 ] ] ], LNew ).

所以行为是:

List1 = []

add_to_list( List1, Index1, Param1, Value1, List2 )
List2 = [
    [ Index1, [ [ Param1, Value1 ] ] ]
]

add_to_list( List2, Index1, Param2, Value2, List3 )
List3 = [
    [ Index1, [ [ Param1, Value1 ], [ Param2, Value2 ] ] ]
]

add_to_list( List3, Index2, Param3, Value3, List4 )
List4 = [
    [ Index1, [ [ Param1, Value1 ], [ Param2, Value2 ] ] ],
    [ Index2, [ [ Param3, Value3 ] ] ]
]

谢谢,thanosQR。

于 2012-10-13T12:30:59.023 回答