简体   繁体   中英

Checking if element is present in list in racket

How to check if an element is present in a list, both taken as input from the function call, without using the lambda? I was trying member? but could not get it.

(define (find-string (lst lst str ua)
    (cond ((member? ua lst) #t)
    (else #f))

First, the way with lambda and ormap (for testing):

; ismember? :: String List-of-Strings -> Bool
(define (ismember1? str strs) (ormap [lambda (s) (string=? s str)] strs) )

Second way, with for/or , without lambda :

(define (ismember2? str strs) 
   (for/or ([s (in-list strs)])
      (string=? s str) ) )

Third way, with member , without lambda :

(define (ismember3? str strs) (if [member str strs] #t #f) )

Refer to the official Racket documentation for member .

Notice that the last version is actually the worst in terms of performance.

The use of member would work it's just that you are adding extra "?" in front of the function none is required

 (member 2 (list 1 2 3 4)) [1]

would return true

another way around is writing ones own recursive function

(define (is-in-list list value)
 (cond
  [(empty? list) false]
  [(= (first list) value) true]
  [else (is-in-list (rest list) value)]))

[1] https://docs.racket-lang.org/reference/pairs.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._member%29%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM