I am trying to write a function in Scheme and Prolog that returns first, middle and last item of a list. E.g., find([4,5,8,7,9],L), L = [4,8,9]
.
I came up with this piece of code for Scheme language, but I am new to Prolog and don't know much, so how I can get the same result in Prolog?
(define (frst L)
(car L))
(define (last L)
(if (null? (cdr L))
(car L)
(last (cdr L))))
(define (nth L x)
(if (= x 1)
(car L)
(nth (cdr L) (- x 1))))
(define (firstMidLast L)
(list (frst L)
(nth L (ceiling (/ (length L) 2)))
(last L)))
Here's another way to do it!
list_first_mid_last(+,?,?,?)
deterministic.We define
list_first_mid_last/4
like this:Let's run a few queries and put Prolog1 and Scheme2 results side-by-side!
Footnote 1: Using swi-prolog version 7.3.11 (64-bit).
Footnote 2: Using the scheme interpreter SCM version 5e5 (64-bit).
Assuming that in the case that the list has even number of items you can choose one of them (in this case the first one), this procedure should work:
Edited per comment from user 'repeat' (i am not versed on Scheme)
The head of the clause instantiates the First item of the list, then
append/3
takes the Last item,length/2
computes the size-1 of the list,>>/2
will divide that size by 2, andnth0/3
will get the Middle item.