Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme to Clojure

Tags:

clojure

scheme

I have a Scheme function that has the following attributes: It counts the number of leaf nodes a nested list structure, ignoring #f. It uses a recursive procedure:

  • If the input is an empty list, this is the base case that returns 0.
  • If the input is a pair whose car is not a list:
    • If the car is #f, we recurse on the cdr and return that.
    • Otherwise we count the car as 1, and add that to the result of recursing on the cdr.
  • Finally, we recurse on both the car and cdr, and add them together.

How can I turn the following code into the programming language Clojure?

(define (x lis)
  (cond ((null? lis) 0) 
        ((not (list? (car lis))) 
         (cond 
          ((eq? (car lis) #f) (x (cdr lis))) 
          (else (+ 1 (x (cdr lis)))))) 
        (else (+ (x (car lis)) (x (cdr lis))))))
like image 359
user1585646 Avatar asked Dec 13 '25 10:12

user1585646


1 Answers

The transparent translation is

(defn x [lis]
  (cond (empty? lis) 0
        (not (coll? (first lis)))
        (if (= (first lis) false)
          (x (rest lis))
          (inc (x (rest lis))))
        :else (+ (x (first lis)) (x (rest lis)))))

Or did you ask about clojure specific solution?

Edited (clojure specific solution ver.1).

(defn x [lis]  
  (count (filter (partial not= false) (flatten lis))))
like image 70
mobyte Avatar answered Dec 16 '25 04:12

mobyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!