Code: Select all
(count (list "a") (explode a)
Code: Select all
(count (list "a") (explode a)
I'll playfully assume you did not mean this:cormullion wrote: I wonder if there's a better way to count the number of occurrences of a character in a string, rather than convert both to lists first:
Code: Select all
> (set 'a (dup "abcdefg" 5))
"abcdefgabcdefgabcdefgabcdefgabcdefg"
> (define (num-chars s) (count (args) (explode s)))
(lambda (s) (count (args) (explode s)))
> (num-chars a "b" "g" "a" "x")
(5 5 5 0)
> _
Code: Select all
> _
Code: Select all
> _
Code: Select all
> _
Code: Select all
> ^D
bash> _
Correct. Converting the strings to lists is indeed the 'roundabout'-ness of which I spoke.m i c h a e l wrote:I'll playfully assume you did not mean this:cormullion wrote: I wonder if there's a better way to count the number of occurrences of a character in a string, rather than convert both to lists first:
Code: Select all
> (set 'a (dup "abcdefg" 5)) "abcdefgabcdefgabcdefgabcdefgabcdefg" > (define (num-chars s) (count (args) (explode s))) (lambda (s) (count (args) (explode s))) > (num-chars a "b" "g" "a" "x") (5 5 5 0) > _
Um, yes. What substances have you been ingesting today? ;-)m i c h a e l wrote: But something more like this:
Imagine the prompt blinking away, patiently waiting.Code: Select all
> _
"Where is michael?", the prompt quietly thinks to itself after some time passes.
After a while, the prompt blurts out, "Here he is! Must have been off in the manual, seeing how to do it."Code: Select all
> _
"Now he's pressing the . . . Control key? Control key. Why would he . . . Not D! Not Control-[click]"Code: Select all
> _
Every way I tried to finagle it, lists ended up crashing the party. I suspect something like the string buffer functions would be the tool of choice, but I'll leave the answer up to one of the club's newrus (newLISP gurus ;-)Code: Select all
> ^D bash> _
m i c h a e l
Code: Select all
(define (num-chars s)
(count (args) (explode s)))
Code: Select all
(define (num-chars str)
(let (result)
(dolist (c (args))
(replace c str "")
(push $0 result -1))
result))
> (num-chars a "b" "g" "a" "x")
(5 5 5 0)
>
... and slowly I am trying to round out the API and make list-only functions work on strings too. The last addition to work on strings was 'push/pop'; 'count', 'rotate' and 'member' are the next and I probably will stop there. For some functions it just doesn't make much sense, like the set functions 'intersect', 'difference' and 'unique' which will always only work on lists or functions working on associations like 'assoc' and 'replace-assoc'.It's a very pleasant aspect of newLISP that you can often use the same function for both lists and strings, and I had to look carefully in the manual before I realised that 'count' was strictly list-only.