Can I divide list into multiple parts in BSL?

81 Views Asked by At

I have the list of values and want to take first x values from it and create (list (listof first x values) (listof next x values) and so on until this list gets empty...).

For example, given this list: (list "a" "b" "c" "d" "e" "f" "g" "h" "t") return this: (list (list a" "b" "c") (list "d" "e" "f") (list "g" "h" "t"))

Thanks in advance :)

2

There are 2 best solutions below

0
On

Remember what a datatype for a list is. Your class is probably doing something like:

;; A IntegerList is one of:
;;   - '()
;;   - (cons Integer IntegerList)

Given that, your template should reflect this structure. I will solve the base case (where we want to turn a list of integers into lists of one integers.

First I will define a 1List datatype as:

;; a 1List is:
;;  - (cons Integer '())

Next, the purpose statement and signature for the function will be:

;; Takes a list of integers and returns a list of 1Lists of the same integers
;; IntegerList -> 1List
(define (make-1list lst)
  ...)

Okay cool. Now we need test cases:

(check-expect (make-1list (list 1 2 3)) (list (list 1) (list 2) (list 3)))
(check-expect (make-1list (list)) (list))
(check-expect (make-1list (list 42)) (list (list 42)))

Finally, I can make my template:

(define (make-1list lst)
    (cond [(null? lst) ...]
          [else        ... (first lst) ... (rest lst) ...]))

(Note that it sometimes makes sense to make some of the template first, to help you guide what tests you need.)

Finally, we can fill in our code:

(define (make-1list lst)
  (cond [(null? lst) '()]
        [else (cons (list (first lst)) (make-1list (rest lst)))]))

And finally, are examples are also tests so we just need to run them to make sure everything works.

Now, since you want to make 3Lists instead of 1Lists, do you see how you can follow this recipe to solve the problem?

  1. Write down your data definition.
  2. Make your purpose statement and signature.
  3. Make your examples.
  4. Make your template.
  5. Write the actual function.
  6. Turn your existing examples into tests.

Following this pattern should help you break the problem down into smaller steps. Good luck.

0
On

Better way to accomplish this task is to use accumulators & recursion.