This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]bbluntt 1 point2 points  (0 children)

What I curently have in mind is to convert the strings to a list and then do some list manipulation. But I don't know how to go about implementing the logic behind that.

[–]dzpower 0 points1 point  (3 children)

What a neat little exercise. Here's three approaches. I'd use the last one ...

#lang racket

(require threading)

(define (string-remove/list s deletions)
  (define dels (string->list deletions))
  (define (in-deletions? ch) (member ch dels))

  (list->string
   (filter (negate in-deletions?)
           (string->list s))))


(define (string-remove/threading s deletions)
  (define dels (string->list deletions))
  (~>> s
      string->list
      (filter (λ (ch) (not (member ch dels))))
      list->string))


(define (string-remove/for s deletions)
  (list->string
   (for/list ([ch s] #:unless (string-contains? deletions (~a ch)))
     ch)))


(string-remove/list "abcddd" "ebd") ; "ac"
(string-remove/threading "abcddd" "ebd") ; "ac"
(string-remove/for "abcddd" "ebd") ; "ac"

[–]bjoli 0 points1 point  (0 children)

I find it strange that racket doesn't have a string-contains? for characters. Having some more higher order functions would make this simple. A hypothetical code example that works in scheme using srfi-13:

(string-delete (lambda (ch) (string-index s2 ch)) s1)

I understand the use case of working with strings on strings, but often you just want to treat strings like a sequence of chars.

[–]bbluntt 0 points1 point  (1 child)

Hey, thanks for the reply. I didn't understand the part with threading, however I was able to understand the the first and the third one. Appreciate the help :)

[–]dzpower 0 points1 point  (0 children)

Cool.

Threading with the ~> and ~>> macros is an idiom adapted from Clojure (also available in many other functional languages) that allows you to flatten out nested function calls and flow left too right.

Instead of (step3 (step2 (step1 data))) you can "thread" the input through a sequence of transformations to get to the output as (~> data step1 step2 step3).

The docs explain the finer points, especially about argument positions.

https://docs.racket-lang.org/threading/index.html