Definition of Prolog IntList

hill (+ IntList) succeeds if IntList consists of monotonically increasing> integers, followed by monotonically decreasing integers. For example,> [1,2,5,8,11,6,3, -1] is a hill, but [1,2,5,8,11,6,9,3, -1] and [1, 2 , 3,4,5,6] are not hills. You can assume that IntList contains only integers.

This is what I have done so far:

hill(List) :-
    increasing(List), decreasing(List).

increasing([H|Tail]) :-
    sm(H,Tail),
    increasing(Tail).
increasing([]).


decreasing([H|Tail]) :-
    gr(H,Tail),
    decreasing(Tail).

decreasing([]).

hill([]).

gr(X,[H|Tail]) :- X>H.
gr(X,[]).

sm(X,[H|Tail]) :- X<H.  
sm(X,[]).  

But that does not work. Logic: A list of numbers hillIF this increasing, then decreasing. How can I say that? This code has increasingand decreasing, but none of them can be both increasing, and decreasing.

Any ideas?

+3
source share
3 answers
hill(L1) :- concatenate(L2,L3,L1), inc(L2), dec(L3).
dec([X|[Y|[]]]) :- X > Y.
dec([X|[Y|L]]) :- X > Y, dec([Y|L]).
inc([X|[Y|[]]]) :- Y > X.
inc([X|[Y|L]]) :- Y > X, inc([Y|L]).
concatenate([],L2,L2).
concatenate([X|L1],L2,[X|L3]) :- concatenate(L1,L2,L3).

It works:)

0

, , , , . increasing decreasing . , , , . . , / . , increasing , . , decreasing, , .

, , , ( , Prolog), , .

OP: , - . L , L , M, , , , N, N < M. Prolog?

, ( SPOILER):


: increasing([])., hill([]). hill(List) :- decreasing(List).. , , . [3, 2, 1]. .

+2

Use !

:- use_module(library(clpfd)).

We do not need to worry about the correctness of recursion, if we use append/3and chain/2as follows:

hill(Zs) :-
   Ascending0 =   [_|_],
   Descending = [M,_|_],
   append(Ascending0,Descending,Zs),
   append(Ascending0,[M],Ascending),
   chain(Ascending ,#<),
   chain(Descending,#>).

Let the queries provided by the OP run!

?- hill([1,2,5,8,11,6,3,-1]).
  true                               % as expected
; false.

?- hill([1,2,5,8,11,6,9,3,-1]).
false.                               % as expected

?- hill([1,2,3,4,5,6]).
false.                               % as expected 
+1
source

Source: https://habr.com/ru/post/1722902/


All Articles