gpt4 book ai didi

combinators - 切割运行时计算值?

转载 作者:行者123 更新时间:2023-12-01 01:59:14 28 4
gpt4 key购买 nike

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

如果我不能使用 cleave,那么我基本上必须这样做:
[ [ [ "deficient" = ] count ] 
[ [ "abundant" = ] count ]
[ [ "perfect" = ] count ]
tri
] dip

这是跛脚和更长,如果键字符串数组更长,会变得非常丑陋和长。此外,重要的是,如果 key 数组是在运行时生成的,那么不进行劈裂是不可能的。
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 说不能将 SOMETHING 应用于运行时计算值时,通常意味着可以更好地编写某些内容。我想这里你要替换cleave带直方图:

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

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

关于combinators - 切割运行时计算值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951947/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com