Reputation: 1
hello I'm a student currently trying to make a function in Dr racket that's purpose is when a letter is selected it turns it into underscore
string(word) string(letter) -> string(answer/underscore)
I've only been able to make this happen with one letter as _ which makes the second check true and I can't figure out how to do multiple letters
(check-expect(underscore "william""li")"_illi__"))
(check-expect(underscore "william" "l")"__ll___))
My code:
(define (anti-omit word letter)
(cond[(string=? word letter)letter]
[(= 1 (string-length word))"_"]
[else
(string-append
(anti-omit (substring word 0 1)letter)
(anti-omit (substring word 1)letter))]))
Upvotes: 0
Views: 396
Reputation: 2137
Here's a stub with a purpose statement, signature, and your tests:
;; String String -> String
;; keeps all letters that occur in l, replaces with "_" otherwise
(check-expect (anti-omit "william" "li") "_illi__")
(check-expect (anti-omit "william" "l") "__ll___")
(define (anti-omit w l)
"")
Since you're using a student language, and as you suggest in the title of the question that you want to recur on the data... you'll need a recursive data-definition:
;; String is one of:
;; - ""
;; - (string-append 1String String)
Complete the definition of this function:
;; String -> String
;; is str equal to "" ?
(define (string-empty? str)
...)
a more restrictive data-definition for other two functions (which correspond to rest and first of a list):
;; NEString is one of:
;; - (string-append 1String "")
;; - (string-append 1String NEString)
Some other functions for you to complete:
;; NEString -> String
;; remove the first 1String from str
(define (string-rest str)
...)
;; NEString -> String
;; the first 1String form str
(define (string-first str)
...)
Now you can make functions like this on Strings:
;; [1String -> 1String] String -> String
;; Applies the function f on each 1String in s
(define (map-str f s)
(cond [(string-empty? s) ""]
[else (string-append (f (string-first s)) (map-str f (string-rest s)))]))
Similarly, complete this definition:
;; 1String String -> Boolean
;; is does 1String occur in String?
(define (member-str e l)
...)
Our "wish list" is complete, and we can compose our helpers to finish the final function:
(define (anti-omit w l)
(map-str (λ (x) (if (member-str x l) x "_")) w))
A similar version that uses explode and implode and doesn't need any of the functions we defined (use this as a reference implementation):
(define (anti-omit-ref w l)
(implode (map (λ (x) (if (member? x (explode l)) x "_")) (explode w))))
Upvotes: 1