标签: lazy-evaluation

在 python 中,我可以使用 tee 延迟生成迭代器的副本吗?

我正在尝试创建一个迭代器,它会延迟创建迭代器的(可能是无限多个)副本。这可能吗?

我知道我可以通过简单地创建任何固定的有限数量的副本

from itertools import tee
iter_copies = tee(my_iter, n=10)
Run Code Online (Sandbox Code Playgroud)

但如果您事先不知道 n 或者 n 是无限的,那么这种情况就会失败。

我通常会尝试一些类似的事情

from itertools import tee

def inf_tee(my_iter):
    while True:
        yield tee(my_iter)[1]
Run Code Online (Sandbox Code Playgroud)

但文档指出,在迭代器上使用 tee 后,原始迭代器将无法再使用,因此这不起作用。


如果您对该应用程序感兴趣:其想法是创建一个惰性函数,可能在pytoolzunzip中使用。我当前的实现可以处理有限数量的无限迭代器(这比 plain 更好),但不能处理无限数量的无限迭代器。如果您对详细信息感兴趣,请参阅以下拉取请求。zip(*seq)

python iterator lazy-evaluation

3
推荐指数
1
解决办法
1336
查看次数

使用严格的 monad 操作无限列表

我有一个f :: [a] -> b对无限列表进行操作的函数(例如take 5takeWhile (< 100) . scanl (+) 0等等)。我想为这个函数提供由严格的单子动作(例如randomIO)生成的值。

这个问题中,我了解到repeatandsequence技巧方法不适用于严格的单子,如下例所示:

import Control.Monad.Identity

take 5 <$> sequence (repeat $ return 1) :: Identity [Int]
-- returns `Identity [1,1,1,1,1]`
-- works because Identity is non-strict

take 5 <$> sequence (repeat $ return 1) :: IO [Int]
 -- returns `*** Exception: stack overflow`
 -- does not work because IO is strict
Run Code Online (Sandbox Code Playgroud)

因此,我考虑在单子上下文“内部”使用该函数。我受到这个循环编程示例的启发并尝试:

let loop …
Run Code Online (Sandbox Code Playgroud)

monads haskell lazy-evaluation strictness conduit

3
推荐指数
1
解决办法
435
查看次数

了解 C# 中 LINQ 的惰性求值

我正在阅读这篇关于 LINQ 的文章,但无法理解查询是如何在惰性求值方面执行的。

因此,我将文章中的示例简化为以下代码:

void Main()
{
    var data =
        from f in GetFirstSequence().LogQuery("GetFirstSequence")
        from s in GetSecondSequence().LogQuery("GetSecondSequence", f)
        select $"{f} {s}";

    data.Dump(); // I use LINQPAD to output the data
}

static IEnumerable<string> GetFirstSequence()
{
    yield return "a";
    yield return "b";
    yield return "c";
}

static IEnumerable<string> GetSecondSequence()
{
    yield return "1";
    yield return "2";
}

public static class Extensions
{
    private const string path = @"C:\dist\debug.log";

    public static IEnumerable<string> LogQuery(this IEnumerable<string> sequence, string tag, string element …
Run Code Online (Sandbox Code Playgroud)

c# linq lazy-evaluation

3
推荐指数
1
解决办法
5476
查看次数

insertUI 中循环生成的observeEvent

当我以响应式方式使用 insertUI 创建新对象时,我创建的所有观察者都工作得很好,如以下虚拟代码所示:

library(shiny)

# Define the UI
ui <- fluidPage(
  actionButton("adder", "Add"),
  tags$div(id = 'placeholder')
)


# Define the server code
server <- function(input, output) {
  rv <- reactiveValues()

  rv$counter <- 0

  observeEvent(input$adder,{
    rv$counter <- rv$counter + 1

    add <- sprintf("%03d",rv$counter)

    filterId <- paste0('adder_', add)
    divId <- paste0('adder_div_', add)
    elementFilterId <- paste0('adder_object_', add)
    removeFilterId <- paste0('remover_', add)

    insertUI(
      selector = '#placeholder',
      ui = tags$div(
        id = divId,
        actionButton(removeFilterId, label = "Remove filter", style = "float: right;"),
        textInput(elementFilterId, label = …
Run Code Online (Sandbox Code Playgroud)

user-interface r insert lazy-evaluation shiny

3
推荐指数
1
解决办法
1029
查看次数

无论如何,“context”和“with_context”之间有什么区别?

这是无论如何Context的文档:

/// Wrap the error value with additional context.
fn context<C>(self, context: C) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static; 
Run Code Online (Sandbox Code Playgroud)
/// Wrap the error value with additional context that is evaluated lazily
/// only once an error does occur.
fn with_context<C, F>(self, f: F) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static,
    F: FnOnce() -> C;
Run Code Online (Sandbox Code Playgroud)

在实践中,不同之处在于with_context需要一个闭包,如无论如何的README所示:

use anyhow::{Context, Result};

fn main() -> Result<()> { …
Run Code Online (Sandbox Code Playgroud)

methods error-handling closures lazy-evaluation rust

3
推荐指数
2
解决办法
498
查看次数

模式匹配元组不是完全懒惰的吗?

我在 Haskell 中遇到了一些非常不直观的行为,我不确定它是否是 Haskell 中的错误。如果这是预期行为,具体是什么导致无限循环?

import Data.Function (fix)

main=putStrLn$show$fst$
    fix (\rec-> (\(a1,a2)->(3,7)) rec)
Run Code Online (Sandbox Code Playgroud)

无限循环,我假设是因为将 rec 模式匹配到 rec (a1,a2) 它评估。但我觉得它不应该需要,因为一切都会匹配。例如,这些都可以正常工作:

    fix (\rec-> (\a->(3,7)) rec)
    fix (\rec-> (\a->let (a1,a2)=a in (3,7)) rec)
Run Code Online (Sandbox Code Playgroud)

有趣的是这退出错误

    fix (\rec-> (\(a1,a2)->(3,7)) undefined)
Run Code Online (Sandbox Code Playgroud)

但是我可以发誓,我遇到这种行为(更复杂)的原始代码在这种情况下实际上会起作用。我可以尝试重新创建它。

haskell lazy-evaluation

3
推荐指数
1
解决办法
111
查看次数

Haskell中的`map`是懒惰的吗?

我一直在研究 Graham Hutton 的 Haskell 编程。它指出

该函数map将函数应用于列表的所有元素

好的,有道理。当然符合我对其他语言地图的了解。

练习之一是实施all :: (a -> Bool) -> [a] -> Bool

有时,如果不是懒惰地完成,一个幼稚的实现可能会无限循环。例如all (<10) [1..]。所以我的第一个实现是:

all p []       = True
all p (x:xs)   | not (p x) = False
               | otherwise = all' p xs
Run Code Online (Sandbox Code Playgroud)

但后来我想到了用函数组合尝试mapand看什么在Haskell非终止的程序会怎么做:

all' :: (a -> Bool) -> [a] -> Bool
all' p = and . map p
Run Code Online (Sandbox Code Playgroud)

出乎我的意料,all' (<10) [1..]很快就回来了False。我实际上希望mapand应用之前尝试创建一个无限列表- 类似于and …

haskell lazy-evaluation higher-order-functions

3
推荐指数
1
解决办法
96
查看次数

为什么这个定点计算不停止?

我是 Haskell 的新手,我有以下代码:

second (x:y:xs) = y : second xs  -- returns every second element of a list
second _ = []

xs = [1,2,3,4] ++ second xs
Run Code Online (Sandbox Code Playgroud)

我期望xs被评估为[1,2,3,4,2,4,4],因为这是固定点,即[1,2,3,4,2,4,4] == [1,2,3,4] ++ second [1,2,3,4,2,4,4]

然而,当我尝试xs在 GHCi 中进行评估时,我得到了

Prelude> xs
[1,2,3,4,2,4,4
Run Code Online (Sandbox Code Playgroud)

但它不会停止计算。

谁能解释为什么这不会停止,有没有一种简单的方法可以使计算停止并返回[1,2,3,4,2,4,4]

haskell infinite-loop lazy-evaluation infinite-recursion fixpoint-combinators

3
推荐指数
1
解决办法
132
查看次数

字典值的惰性评估?

假设我有以下 dict d={'a': heavy_expression1, 'b': heavy_expression2}

如何包装表达式,以便在访问它们后对其进行求值,并且在此之后不执行求值?

d['a'] # only here heavy_expression1 is executed
d['a'] # no execution here, already calculated
Run Code Online (Sandbox Code Playgroud)

我需要使用lambda发电机吗?

python lazy-evaluation python-3.x

3
推荐指数
1
解决办法
912
查看次数

为什么 Java 中的“orElseThrow()”方法采用“Supplier”作为参数而不是“Exception”?

为什么orElseThrow()Java中的方法采用aSupplier作为参数而不是an Exception?这就是问题,我找到的最佳答案就在这里,说明

这里的首要概念是,通过提供方法引用(或函数),可以延迟初始化它。如果不需要,则无需创建 Exception 对象。仅在需要时创建它。

然而我还是不明白。为什么对象创建不能偷懒?

java lambda lazy-evaluation option-type

3
推荐指数
1
解决办法
2179
查看次数