切割运行时计算值? [英] Cleave a run-time computed value?

查看:87
本文介绍了切割运行时计算值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cleave是用于最小化代码重复的真正有用的组合器.假设我要分类丰富,完善,不足的数字:

Cleave is a really useful combinator for minimising code duplication. Suppose I want to classify 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无法编译,因为无法对运行时计算值应用劈裂".

range>adp-classes does not compile because "cannot apply cleave to a run-time computed value".

如果我不能使用分裂,那么我就必须做:

If I can't use cleave, then I have to essentially do:

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

这是la脚的和更长的,如果键串的数组更长,它将变得非常丑陋和漫长.另外,重要的是,如果在运行时生成键数组,则不进行分裂就不可能做到这一点.

Which is lame and longer, and would get really ugly and long if the array of key-strings was longer. Also, importantly, doing it without cleave is impossible if the array of keys is generated at run-time.

print-adp-stats类似:如果没有cleave,则必须在源代码中使用此文字:

Similarly for print-adp-stats: without cleave I would have to have this literal lying around in my source:

{
    [ "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来作为运行时计算值?我是否可以通过其他方式最大程度地减少丑陋的重复,同时仍然允许在运行时进行计算?

Is there a combinator to replace cleave for run-time computed values? Can I minimise the ugly duplication some other way, while still allowing computation at run-time?

推荐答案

cleave在这里可能不是正确的答案.当Factor说不能在运行时计算值上应用某些东西" 时,这意味着可以更好地编写某些内容.我想在这里您想将cleave替换为直方图:

cleave is likely not the right answer here. When Factor says cannot apply SOMETHING to a run-time computed value most often it means something can be written better. I think here you want to replace cleave with histogram:

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

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

这篇关于切割运行时计算值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆