Product of squares of odd elements in list in Scheme -


i wanted write code in scheme writes square odd elements in list.for example (list 1 2 3 4 5) list should write 225.for purpose write code:

(define (square x)(* x x))  (define (product-of-square-of-odd-elements sequence)   (cond[(odd? (car sequence)) '() (product-of-square-of-odd-elements (cdr sequence))]        [else ((square (car sequence)) (product-of-square-of-odd-elements (cdr sequence)))])) 

for run write (product-of-square-of-odd-elements (list 1 2 3 4 5)) , error this:

car: contract violation   expected: pair?   given: '() 

what should make code run properly? thank answers.

first of all, need proper formatting:

(define (square x) (* x x))  (define (product-of-square-of-odd-elements sequence)   (cond     [(odd? (car sequence))      '() (product-of-square-of-odd-elements (cdr sequence))]     [else      ((square (car sequence)) (product-of-square-of-odd-elements (cdr sequence)))])) 

now there multiple issues code:

  1. you trying work recursively on sequence, missing termination case: happens when pass '() - empty sequence? source of error: cannot access first element of empty sequence.

  2. you need build result somehow: you're sending '() nirvana in first branch of cond , put value function call position in second.

so let's start scratch:

you process sequence recursively, need handle 2 cases:

(define (fn seq)   (if (null? seq)        ;; termination case        ;; recursive case        )) 

let's take recursive case first: need compute square , multiply rest of squares (that you'll compute next).

(* (if (odd? (car seq)          (square (car seq))          1)    (fn (cdr seq))) 

in termination case have no value square. use unit value of multiplication: 1

this not solution, can transform tail recursive form , use higher order functions abstract recursion altogether. think that's enough start.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -