许多现代编程语言允许我们处理潜在的无限列表并对它们执行某些操作。
示例[Python]:
EvenSquareNumbers = ( x * x for x in naturals() if x mod 2 == 0 )
这样的列表可以存在,因为只计算实际需要的元素。 (懒惰的评价)
我只是想知道是否有可能(或甚至以某些语言练习)将懒惰评估的机制扩展到算术。
实施例:
鉴于无数的偶数列表evens = [ x | x <- [1..], even x ]
我们无法计算
length evens
因为此处所需的计算永远不会终止。
但我们实际上可以确定
length evens > 42
无需评估整个length
字词。
这可能用任何语言吗?那么Haskell呢?
编辑:使要点更清楚:问题不在于如何确定惰性列表是否短于给定数字。它是关于使用传统内置函数的方式,数字计算是懒惰的。
sdcvvc展示了Haskell的解决方案:
data Nat = Zero | Succ Nat deriving (Show, Eq, Ord)
toLazy :: Integer -> Nat
toLazy 0 = Zero
toLazy n = Succ (toLazy (n-1))
instance Num Nat where
(+) (Succ x) y = Succ (x + y)
(+) Zero y = y
(*) Zero y = Zero
(*) x Zero = Zero
(*) (Succ x) y = y + (x * y)
fromInteger = toLazy
abs = id
negate = error "Natural only"
signum Zero = Zero
signum (Succ x) = Succ Zero
len [] = Zero
len (_:x') = Succ $ len x'
-- Test
len [1..] < 42
这还可以用其他语言吗?
答案 0 :(得分:8)
您可以创建自己的自然数字......
data Nat = Zero | Succ Nat deriving (Show, Eq, Ord)
len :: [a] -> Nat
len = foldr (const Succ) Zero
toLazy :: Int -> Nat
toLazy 0 = Zero
toLazy n = Succ (toLazy (n-1))
a = len [1..] > toLazy 42
然后a是真的,多亏了懒惰的评价。 len使用foldr是至关重要的,foldl不适用于无限列表。你也可以做一些算术(未测试):
instance Num Nat where
(+) (Succ x) y = Succ (x + y)
(+) Zero y = y
(*) Zero y = Zero
(*) x Zero = Zero
(*) (Succ x) y = y + (x * y)
fromInteger = toLazy
abs = id
negate = error "Natural only"
signum Zero = Zero
signum (Succ x) = Succ Zero
例如,2 *无穷大+ 3是无穷大:
let infinity = Succ infinity
*Main> 2 * infinity + 3
(Succ (Succ (Succ ^cCc (Succ (Succ (SuccInterrupted.
第二个解决方案
另一个解决方案是使用()列表作为惰性自然数。
len = map (const ())
toLazy n = replicate n ()
a = len [1..] > toLazy 42
检查Hackage。
编辑:添加了实例Num。
EDIT2:
将第二个解决方案翻译成Python:
import itertools
def length(x):
return itertools.imap(lambda: (), x)
def to_lazy(n):
return itertools.chain([()] * n)
要添加数字,请使用itertools.chain进行乘法,使用itertools.product。这不像Haskell那样漂亮,但它确实有效。
在使用闭包的任何其他严格语言中,您可以使用type() - &gt;来模拟懒惰。而不是。使用它可以将第一个解决方案从Haskell转换为其他语言。然而,这很快就会变得难以理解。
答案 1 :(得分:3)
如果不是懒惰,我认为这可以在F#中使用:
type Nat = Zero | Succ of Nat
let rec toLazy x =
if x = 0 then Zero
else Succ(toLazy(x-1))
type Nat with
static member (+)(x:Nat, y:Nat) =
match x with
| Succ(a) -> Succ(a+y)
| Zero -> y
static member (*)(x:Nat, y:Nat) =
match x,y with
| _, Zero -> Zero
| Zero, _ -> Zero
| Succ(a), b -> b + a*b
module NumericLiteralQ =
let FromZero() = toLazy 0
let FromOne() = toLazy 1
let FromInt32(x:int) = toLazy x
let rec len = function
| [] -> 0Q
| _::t -> 1Q + len t
printfn "%A" (len [1..42] < 100Q)
printfn "%A" (len [while true do yield 1] < 100Q)
但是因为我们需要懒惰,所以它扩展到了这个:
let eqLazy<'T> (x:Lazy<'T>) (y:Lazy<'T>) : bool = //'
let a = x.Force()
let b = y.Force()
a = b
type Nat = Zero | Succ of LazyNat
and [<StructuralComparison(false); StructuralEqualityAttribute(false)>]
LazyNat = LN of Lazy<Nat> with
override this.GetHashCode() = 0
override this.Equals(o) =
match o with
| :? LazyNat as other ->
let (LN(a)) = this
let (LN(b)) = other
eqLazy a b
| _ -> false
interface System.IComparable with
member this.CompareTo(o) =
match o with
| :? LazyNat as other ->
let (LN(a)) = this
let (LN(b)) = other
match a.Force(),b.Force() with
| Zero, Zero -> 0
| Succ _, Zero -> 1
| Zero, Succ _ -> -1
| Succ(a), Succ(b) -> compare a b
| _ -> failwith "bad"
let (|Force|) (ln : LazyNat) =
match ln with LN(x) -> x.Force()
let rec toLazyNat x =
if x = 0 then LN(lazy Zero)
else LN(lazy Succ(toLazyNat(x-1)))
type LazyNat with
static member (+)(((Force x) as lx), ((Force y) as ly)) =
match x with
| Succ(a) -> LN(lazy Succ(a+ly))
| Zero -> lx
module NumericLiteralQ =
let FromZero() = toLazyNat 0
let FromOne() = toLazyNat 1
let FromInt32(x:int) = toLazyNat x
let rec len = function
| LazyList.Nil -> 0Q
| LazyList.Cons(_,t) -> LN(lazy Succ(len t))
let shortList = LazyList.of_list [1..42]
let infiniteList = LazyList.of_seq (seq {while true do yield 1})
printfn "%A" (len shortList < 100Q) // true
printfn "%A" (len infiniteList < 100Q) // false
这说明了为什么人们只在Haskell中写这个东西。
答案 2 :(得分:2)
你可以通过尝试从evens中获得超过42个元素来达到你想要的效果。
答案 3 :(得分:1)
我不确定我理解你的问题,但让我们试一试。也许你正在寻找溪流。我只会说FP语言系列中的Erlang,所以......
esn_stream() ->
fun() -> esn_stream(1) end.
esn_stream(N) ->
{N*N, fun() -> esn_stream(N+2) end}.
调用流总是返回下一个元素,并且应该调用以检索下一个元素。这样你就可以实现懒惰的评估。
然后您可以将is_stream_longer_than函数定义为:
is_stream_longer_than(end_of_stream, 0) ->
false;
is_stream_longer_than(_, 0) ->
true;
is_stream_longer_than(Stream, N) ->
{_, NextStream} = Stream(),
is_stream_longer_than(NextStream, N-1).
结果:
1> e:is_stream_longer_than(e:esn_stream(), 42).
true
2> S0 = e:esn_stream().
#Fun<e.0.6417874>
3> {E1, S1} = S0().
{1,#Fun<e.1.62636971>}
4> {E2, S2} = S1().
{9,#Fun<e.1.62636971>}
5> {E3, S3} = S2().
{25,#Fun<e.1.62636971>}