Checking if element is present in list in racket
Asked Answered
G

2

5

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))
Goffer answered 17/3, 2016 at 19:47 Comment(2)
It seems that you're trying to specify the type of each parameter in the procedure declaration? it doesn't work like that in Racket...Shirelyshirey
This may help.Melisma
K
4

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

Klemperer answered 13/10, 2017 at 12:49 Comment(2)
I am unsure if you are asking a question or not. Please avoid sentences that require a questionmark at their end.Oldworld
? was an operator not for question updated by adding quote on itKlemperer
J
3

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.

Jeffers answered 31/3, 2018 at 22:21 Comment(1)
the OP's order of arguments is reversed though. so their intended function could be better named "contains".Thorvaldsen

© 2022 - 2024 — McMap. All rights reserved.