切割 运行 次计算值?

Cleave a run-time computed value?

Cleave 是一个非常有用的组合器,可以最大程度地减少代码重复。假设我要分类 Abundant, Perfect, Deficient numbers:

USING: arrays assocs combinators formatting io kernel math
math.order math.primes.factors math.ranges sequences ;
IN: adp

CONSTANT: ADP { "deficient" "perfect" "abundant" }

: proper-divisors ( n -- seq )
  dup zero? [ drop { } ] [ divisors dup length 1 - head ] if ;

: adp-classify ( n -- a/d/p )
  dup proper-divisors sum <=>
  { +lt+ +eq+ +gt+ } ADP zip
  H{ } assoc-clone-like at ;

: range>adp-classes ( n -- seq )
  1 swap 1 <range> [ adp-classify ] map
  ADP dup
  [
    [
      [ = ]     curry
      [ count ] curry
    ] map
    cleave 3array
  ] dip
  swap zip H{ } assoc-clone-like ;

: print-adp-stats ( seq -- )
  ADP [
   [ dup [ swap at ] dip swap "%s: %s" sprintf ] curry
  ] map cleave
  [ print ] tri@ ;

range>adp-classes 无法编译,因为 "cannot apply cleave to a run-time computed value"。

如果我不能使用 cleave,那么我基本上必须这样做:

[ [ [ "deficient" = ] count ] 
  [ [ "abundant" = ] count ]
  [ [ "perfect" = ] count ]
  tri
] dip

它又长又蹩脚,如果键字符串数组更长,它会变得非常丑陋和长。此外,重要的是,如果键数组是在 运行 时生成的,那么不进行切割是不可能的。

print-adp-stats 类似:如果没有 cleave,我将不得不在我的源代码中放置以下文字:

{
    [ "deficient" dup [ swap at ] dip swap "%s: %s" sprintf ]
    [ "perfect" dup [ swap at ] dip swap "%s: %s" sprintf ]
    [ "abundant" dup [ swap at ] dip swap "%s: %s" sprintf ]
}

总收入。

是否有一个组合器可以用 cleave 替换 运行 时间的计算值?我可以通过其他方式最小化丑陋的重复,同时仍然允许在 运行 时间进行计算吗?

cleave 在这里可能不是正确的答案。当 Factor 说 cannot apply SOMETHING to a 运行-time computed value 通常这意味着可以写得更好。我想在这里你想用直方图替换 cleave:

IN: scratchpad 100 [ { "abundant" "deficient" "perfect" } random ] replicate 
    histogram

--- Data stack:
H{ { "deficient" 33 } { "perfect" 30 } { "abundant" 37 } }