简体   繁体   中英

Prolog: Split a list of size N into two lists of known size K and N-K

I have a list of integers, Keys, and want to split it into two lists ListOfReqKeys and ListOfRewKeys as described in the title.

Keys =[1, 1, 3, 9, 1, 15]
ReqK = 3
ListOfReqKeys = [1, 1, 3], ListOfRewKeys = [9, 1, 15]

The length of those two lists is known, its ReqK and RewK respectively.

append(ListOfReqKeys, ListOfRewKeys, Keys),
atom_codes(At, ListOfReqKeys),
atom_number(At, ReqK).

Is there a built in predicate or a faster way of doing that?

There is no splitting. There is only appending.

Splitting a list of length N into a prefix of length K will necessarily leave the suffix with length NK - there's no need to measure / create 1 it so. It will just be so, by construction.

Thus,

split( K, L, A, B):-
   append( A, B, L),
   length(A, K).

Simple, isn't it. But wait, can it be improved upon? Without adding or removing anything from it? What else can we do with it?

1 hint: have you ever tried length(X, 2) ? length(X, N) ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM