【问题标题】:Cleave a run-time computed value?切割运行时计算值?
【发布时间】:2016-10-23 10:42:18
【问题描述】:

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&gt;adp-classes 无法编译,因为“无法将 cleave 应用于运行时计算值”。

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

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

如果键字符串数组更长,它会变得很长而且很长,而且会变得非常丑陋和长。另外,重要的是,如果键数组是在运行时生成的,那么不使用 cleave 是不可能的。

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 的运行时计算值?我可以通过其他方式最小化丑陋的重复,同时仍然允许在运行时计算吗?

【问题讨论】:

    标签: combinators factor-lang


    【解决方案1】:

    cleave 在这里可能不是正确的答案。当 Factor 说 不能将 SOMETHING 应用到运行时计算值 时,这通常意味着可以编写更好的东西。我想在这里你想用直方图替换cleave

    IN: scratchpad 100 [ { "abundant" "deficient" "perfect" } random ] replicate 
        histogram
    
    --- Data stack:
    H{ { "deficient" 33 } { "perfect" 30 } { "abundant" 37 } }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 2011-05-20
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      相关资源
      最近更新 更多