In: Computer Science
You must write each of the following scheme functions. You must use only basic scheme functions, do not use third-party libraries to support any of your work. Do not use any function with side effects.
This problem need to use DrRacket software. Racket Language.
Write a function named (first-n L1 N) that returns the first N elements of L1. If N is negative, return the empty list. If N exceeds the length of L1 return all elements of L1.
(first-n '(a b c d e f) 3) ---> (a b c) (first-n '(a b c d e f) -3) ---> () (first-n '(a b c d e f) 33) ---> (a b c d e f) (first-n '() 0) ---> ()
Write a function named (forget-n L1 N) that returns the elements of L1 except for the first N. If N is negative, return all elements. If N exceeds the length of L1 return the empty list.
(forget-n '(a b c d e f) 3) ---> (d e f) (forget-n '(a b c d e f) -3) ---> (a b c d e f) (forget-n '(a b c d e f) 33) ---> () (forget-n '() 0) ---> ()
1)
Code:
#lang scheme
(define count 1) ;;Initialized count = 1 to keep track our traversal of list
(define (first-n L1 N) ;;MAIN_FUNCTION
(first L1 N count)) ;;calls sub-function Which returns first
N-number of elements of list
(define (first L1 N count) ;;SUB_FUNCTION
(cond ((null? L1) L1) ;;if list is empty returns List
((< N 0) '()) ;;if (N < 0) RETURNS NULL LIST
((= N 0) '()) ;;if (N == 0) reurns NULL list
((= N 1) (car L1)) ;;if (N == 1) Returns 1st element
((= N count) (cons (car L1) '())) ;;if (N == count) returns list
which contains elelemnt at index N
(else (cons (car L1) (first (cdr L1) N (+ 1 count)))))) ;;else construct list with first element and continue
Snapshot of Code and Output:
2)
CODE:
(define count 1) ;;Initialized count = 1 to keep track our traversal of list
(define (forget-n L1 N) ;;MAIN_FUNCTION
(forget L1 N count)) ;;calls sub-function Which returns elements of
list except for the first N
(define (forget L1 N count) ;;SUB_FUNCTION
(cond ((null? L1) '()) ;;if list is empty returns NULL
((< N 0) L1) ;;if (N < 0) RETURNS ENTIRE LIST
((= N 0) L1) ;;if (N == 0) reurns enire list
((= N 1) (cdr L1)) ;;if (N == 1) Returns entire list except 1st
element
((= N count) (cdr L1)) ;;if (N == count) returns rest of the list
index starting from count + 1
(else (forget (cdr L1) N (+ 1 count))))) ;;else continue
Snapshot of Code and Output: