Skip to content

Bad Scheme

12 March, 2011

I am so ashamed 😐

(define string-tokenize
  (lambda (s delims)
    (letrec ((string-tokenize-dirty 
              (lambda (s delims)
                (cond ((null? s) (list '()))
                      ((let ((tokens (string-tokenize-dirty (cdr s) delims)))
                         (if (member (car s) delims)
                             (if (not (null? (car tokens))) (cons '() tokens)
                                 tokens)
                             (cons (cons (car s) (car tokens)) (cdr tokens)))))))))
      (let ((tokens (string-tokenize-dirty (string->list s) (string->list delims))))
        (map list->string (if (null? (car tokens)) (cdr tokens) tokens))))))


> (string-tokenize " a few good men +b*c+d d " " *+")
("a" "few" "good" "men" "b" "c" "d" "d")

Any advice on how to make this tail-recursive?
Also, how can I manipulate strings like lists?

Advertisements
4 Comments leave one →
  1. 12 March, 2011 10:53 PM

    Try this approach: a function to convert the string to the list of letters (I guess that this exists), another function to group elements from a list into sublists by a test with the car of each sublist (see groupBy in Haskell), then a filter to select only the good words, then a function to convert from a list of letters to a string and map this to the filtered list.

    I’ll give some code at a later time if it is still needed.

  2. Vlad permalink
    13 March, 2011 1:52 AM

    string->list might come in handy.

  3. danf permalink*
    13 March, 2011 1:39 PM

    Hmm, I’m already using string->list and list->string and doing the map (line 12).

    But, could you please explain the logic of what you’re doing?
    What do you mean by grouping elements from a list by some predicate? The example here [1] is not exactly helpful. I would need to first map across the string of chars with a function that says in which bucket I should put it and then groupBy that.

    And anyway, even assuming I could do that, how would that make my function tail-recursive?

    [1] http://zvon.org/other/haskell/Outputlist/groupBy_f.html

  4. 13 March, 2011 5:24 PM

    Always use [1] or equivalent. Then go on Hackage and lookup the code for the function [2]. The groupBy function is tail-recursive, string->list and list->string are tail-recursive, filters and maps are always tail-recursive.

    [1]: http://haskell.org/hoogle/
    [2]: http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/Data-List.html#groupBy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: