#:g1: dylanでL-99 (P09 連続して現われる要素を纏める)

Posted 2008-06-04 10:25:00 GMT

-(http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html)
Perlのjoin的なものがないので、自作してみました。
なんだか無闇に長い…。

#(a:, a:, a:, a:, b:, c:, c:, a:, a:, d:, e:, e:, e:, e:).pack
//=>#(#(#"a", #"a", #"a", #"a"), #(#"b"), #(#"c", #"c"), #(#"a", #"a"), #(#"d"), #(#"e", #"e", #"e", #"e"))
#[a:, a:, a:, a:, b:, c:, c:, a:, a:, d:, e:, e:, e:, e:].pack
//=> #[#(#"a", #"a", #"a", #"a"), #(#"b"), #(#"c", #"c"), #(#"a", #"a"), #(#"d"), #(#"e", #"e", #"e", #"e")]
"aaaabccaadeeee".pack
//=> "aaaa,b,cc,aa,d,eeee"

// Code module: l99-09

define generic pack (sequence :: <sequence>) => (result :: <sequence>);

define method pack (sequence :: <string>) => (result :: <string>) if (sequence.empty?) sequence else join(sequence.pack1, ",") end if end method pack;

define method pack (sequence :: <sequence>) => (result :: <sequence>) if (sequence.empty?) sequence else as(select (sequence by instance?) <list> => <list>; <vector> => <vector>; end select, sequence.pack1) end if end method pack;

define function pack1 (sequence :: <sequence>) => (result :: <sequence>) let prev = sequence.first; let res = make(<deque>); let tem = make(<deque>); for (x in sequence) unless (x = prev) push-last(res, as(<list>, tem)); tem := make(<deque>); end unless; push-last(tem, x); prev := x; end for; as(<list>, push-last(res, as(<list>, tem))); end function pack1;

define generic join (sequence :: <sequence>, delim :: <string>) => (result :: <sequence>);

define method join (sequence :: <sequence>, delim :: <string>) => (result :: <string>) let result = make(<deque>); for (c in sequence) push-last(result, c); push-last(result, delim); finally result.pop-last; apply(concatenate-as, <string>, result); end for end method join;


comments powered by Disqus