伸展单词和引用范围

时间:2016-04-24 00:54:05

标签: factor-lang

要在Stretch the word播放,我已经定义了以下字词,尝试通过与this answer相同的方法解决问题:

USING: kernel math sequences sequences.repeating ;
IN: stretch-words

! "bonobo" -> { "b" "bo" "bon" "bono" "bonob" "bonobo" }
: ascend-string ( string -- ascending-seqs )
    dup length 1 + iota [ 0 swap pick subseq ] map
    [ "" = not ] filter nip ;

! expected: "bonobo" -> "bonoobbooo"
! actual:   "bonobo" -> "bbbooonnnooobbbooo"
: stretch-word ( string -- stretched ) 
    dup ascend-string swap zip
    [ 
      dup first swap last 
      [ = ] curry [ dup ] dip count 
      repeat 
    ] map last ;

stretch-word应该按照字符串中该位置出现的次数重复字符串中的字符。但是,我的实现是重复它获得的1string的所有实例。

我觉得这很容易在因子中实现,但我无法弄明白。我该如何做到我想要的呢?

2 个答案:

答案 0 :(得分:2)

嗯......不是很棒的高尔夫球,但它有效......

首先,我对ascend-string做了一个小改动,所以它将字符串留在堆栈上:

: ascend-string ( string -- string ascending-seqs )
    dup length 1 + iota [ 0 swap pick subseq ] map
    [ "" = not ] filter ;

所以stretch-word可以像这样工作:

: stretch-word ( string -- stretched ) 
    ascend-string zip         ! just zip them in the same order
    [ 
      first2 over             ! first2 is the only golf I could make :/
      [ = ] curry count       ! same thing
      swap <array> >string    ! make an array of char size count and make it a string
    ] map concat ;            ! so you have to join the pieces

编辑: 我认为问题是使用重复来完成这项工作。

答案 1 :(得分:1)

: ascend-string ( string -- seqs )
    "" [ suffix ] { } accumulate*-as  ;
: counts ( string -- counts )
    dup ascend-string [ indices length ] { } 2map-as ;
: stretch-word ( string -- stretched )
    [ counts ] keep [ <string> ] { } 2map-as concat ;
"bonobo" stretch-word print
bonoobbooo

indices length也可能是[ = ] with count