How to get the first, middle and last element of a list scheme and prolog?

后端 未结 2 1663
面向向阳花
面向向阳花 2021-01-21 05:25

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 w

2条回答
  •  清歌不尽
    2021-01-21 05:44

    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)

    find([First|List], [First, Middle, Last]):-
      append(_, [Last], [First|List]),
      length(List, Length),
      NLength is Length >> 1,
      nth0(NLength, [First|List], Middle).
    

    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, and nth0/3 will get the Middle item.

提交回复
热议问题