user3457749
user3457749

Reputation: 1043

Finding the same elements in two list in racket

Assume (list 'red 'blue 'green 'yellow) and (list 'black 'red 'orange 'green), then it should produce 2 since there are 2 same elements. I only know how to find the same elements in the exact same place as follows:

(define (helper l1 l2)
  (cond
    [(equal? l1) empty]
    [(equal? l2) empty]
    [(equal? (first l1) (first l2)) true]
    [else (rest l1) (rest l2)]))

Help please. :)

Upvotes: 0

Views: 1288

Answers (2)

Satria Pito
Satria Pito

Reputation: 1

this my code for finding the same elements in two list on racket

(define (cek x y)
 (cond
 [(null? y) 0]
 [(eq? x (car y)) (+ 1 (cek x (cdr y)))]
 [else (cek x (cdr y))]
 )
)
(define (sifat x y)
 (cond
 [(null? x) 0]
 [else (+ (cek (car x) y) (sifat (cdr x) y))]
 )
)

Upvotes: -1

kayleefrye
kayleefrye

Reputation: 85

In case you're not doing this as a homework exercise, here's Óscar López' code using Racket's set library.

#lang racket

(require racket/set)

(define number-same (compose1 length set-intersect))

(number-same '(red blue green yellow)
             '(black red orange green))

Upvotes: 3

Related Questions