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?
4 Comments
leave one →
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.
string->list might come in handy.
Hmm, I’m already using
string->listandlist->stringand 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
Always use [1] or equivalent. Then go on Hackage and lookup the code for the function [2]. The
groupByfunction is tail-recursive,string->listandlist->stringare 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