Checking if the difference between consecutive elements is the same

前端 未结 2 1742
后悔当初
后悔当初 2021-01-24 09:30

I am new to using arithmetic in Prolog.

I’ve done a few small programs, but mostly involving logic. I am trying to implement a function that will return true

2条回答
  •  猫巷女王i
    2021-01-24 10:02

    You were very close with your second attempt. It should have been

    samediffs( [X,  Y | Rest], Result):-
        Result is Y - X,
        samediffs( [Y | Rest], Result).
    

    And you don't even need "to split the first two elements from the list". This will take care of itself.

    How? Simple: calling samediffs( List, D), on the first entry into the predicate, the not yet instantiated D = Result will be instantiated to the calculated difference between the second and the first element in the list by the call Result is Y - X.

    On each subsequent entry into the predicate, which is to say, for each subsequent pair of elements X, Y in the list, the call Result is Y - X will calculate the difference for that pair, and will check the numerical equality for it and Result which at this point holds the previously calculated value.

    In case they aren't equal, the predicate will fail.

    In case they are, the recursion will continue.

    The only thing missing is the base case for this recursion:

    samediffs( [_], _Result).  
    samediffs( [], _Result).
    

    In case it was a singleton (or even empty) list all along, this will leave the differences argument _Result uninstantiated. It can be interpreted as a checking predicate, in such a case. There's certainly no unequal differences between elements in a singleton (or even more so, empty) list.


    In general, ......

    recursion(A, B):- base_case( A, B).
    
    recursion(  Thing,  NewThing):-
      combined( Thing,             Shell, Core),
      recursion(                          Core, NewCore),
      combined(         NewThing,  Shell,       NewCore).
    

    ...... Recursion!

提交回复
热议问题