我正在尝试创建一个迭代器,它会延迟创建迭代器的(可能是无限多个)副本。这可能吗?
我知道我可以通过简单地创建任何固定的有限数量的副本
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)
我有一个f :: [a] -> b对无限列表进行操作的函数(例如take 5,takeWhile (< 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) 我正在阅读这篇关于 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) 当我以响应式方式使用 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) 这是无论如何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) 我在 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)
但是我可以发誓,我遇到这种行为(更复杂)的原始代码在这种情况下实际上会起作用。我可以尝试重新创建它。
我一直在研究 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)
但后来我想到了用函数组合尝试map和and看什么在Haskell非终止的程序会怎么做:
all' :: (a -> Bool) -> [a] -> Bool
all' p = and . map p
Run Code Online (Sandbox Code Playgroud)
出乎我的意料,all' (<10) [1..]很快就回来了False。我实际上希望map在and应用之前尝试创建一个无限列表- 类似于and …
我是 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
假设我有以下 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发电机吗?
为什么orElseThrow()Java中的方法采用aSupplier作为参数而不是an Exception?这就是问题,我找到的最佳答案就在这里,说明
这里的首要概念是,通过提供方法引用(或函数),可以延迟初始化它。如果不需要,则无需创建 Exception 对象。仅在需要时创建它。
然而我还是不明白。为什么对象创建不能偷懒?
lazy-evaluation ×10
haskell ×4
python ×2
c# ×1
closures ×1
conduit ×1
insert ×1
iterator ×1
java ×1
lambda ×1
linq ×1
methods ×1
monads ×1
option-type ×1
python-3.x ×1
r ×1
rust ×1
shiny ×1
strictness ×1