对可变参数的解构迭代,如 D

如何解决对可变参数的解构迭代,如 D

假设我想处理一个可变参数函数,该函数交替传递 1 个或多个间隔的开始和结束值,并且它应该返回这些间隔中的一系列随机值。您可以将输入想象成一个扁平的元组序列,所有元组元素分布在一个范围内。

import std.meta; //variadic template predicates
import std.traits : isFloatingPoint;
import std.range;

auto randomIntervals(T = U[0],U...)(U intervals)
if (U.length/2 > 0 && isFloatingPoint!T && NoDuplicates!U.length == 1) {
    import std.random : uniform01;
    
    T[U.length/2] randomValues;
    // split and iterate over subranges of size 2
    foreach(i,T start,T end; intervals.chunks(2)) {   //= intervals.slide(2,2)
        randomValues[i] = uniform01 * (end - start) + start,}
    return randomValues.dup;
}

例子不重要,我只用它来解释。块大小可以是任何有限的正 size_t,而不仅仅是 2 并且更改块大小应该只需要更改 foreach 循环中循环变量的数量。

在上面的这种形式中,它不会编译,因为它只需要一个参数(一个范围)到 foreach 循环。我想要的是自动使用或推断滑动窗口作为元组的东西,从给定的循环变量的数量派生,并用范围/数组的下一个元素填充附加变量+允许附加索引,可选。根据 documentation 元组范围允许将元组元素销毁为 foreach-loop-variables 所以我想到的第一件事是将范围变成一个元组序列,但没有找到一个方便的函数。

是否有一种简单的方法可以将解构的子范围(如我的示例代码所示如此简单)与索引一起循环?或者是否有一个(标准库)函数可以将范围拆分为相等大小的枚举元组?如何轻松地将子范围的范围转换为元组范围?

在这种情况下是否可以使用 std.algorithm.iteration.map(编辑:使用一个简单的函数参数来映射而不访问元组元素)?

编辑:我想忽略不适合整个元组的最后一个块。它只是没有迭代。

编辑:不是,我不能自己编程,我只希望有一个简单的符号,因为这个循环多个元素的用例非常有用。如果在 D 中像 JavaScript 一样有“传播”或“休息”运算符之类的东西,请告诉我!

谢谢。

解决方法

chunksslide 返回 Range,而不是元组。它们的最后一个元素可以包含小于指定的大小,而元组具有固定的编译时大小。

如果您需要解构,则必须实现自己的返回元组的块/幻灯片。要向元组显式添加索引,请使用 enumerate。下面是一个例子:

import std.typecons,std.stdio,std.range;

Tuple!(int,int)[] pairs(){
    return [
        tuple(1,3),tuple(2,4),tuple(3,5)
    ];
}

void main(){
    foreach(size_t i,int start,int end; pairs.enumerate){
        writeln(i,' ',start,end);
    }
}

编辑:

正如 BioTronic 所说,使用 map 也是可能的:

foreach(i,end; intervals
                       .chunks(2)
                       .map!(a => tuple(a[0],a[1]))
                       .enumerate){
,

(作为单独的答案添加,因为它与我之前的答案明显不同,并且不适合评论)

在阅读您的评论和迄今为止对答案的讨论后,在我看来,您寻求的是类似于以下 staticChunks 函数:


unittest {
    import std.range : enumerate;
    size_t index = 0;
    foreach (i,a,b,c; [1,2,3,1,3].staticChunks!3.enumerate) {
        assert(a == 1);
        assert(b == 2);
        assert(c == 3);
        assert(i == index);
        ++index;
    }
}

import std.range : isInputRange;

auto staticChunks(size_t n,R)(R r) if (isInputRange!R) {
    import std.range : chunks;
    import std.algorithm : map,filter;
    return r.chunks(n).filter!(a => a.length == n).map!(a => a.tuplify!n);
}


auto tuplify(size_t n,R)(R r) if (isInputRange!R) {
    import std.meta : Repeat;
    import std.range : ElementType;
    import std.typecons : Tuple;
    import std.array : front,popFront,empty;
    
    Tuple!(Repeat!(n,ElementType!R)) result;

    static foreach (i; 0..n) {
        result[i] = r.front;
        r.popFront();
    }
    assert(r.empty);

    return result;
}

请注意,这也处理最后一个块的大小不同,如果只是默默地扔掉它。如果这种行为是不可取的,请移除 filter,并在 tuplify 内处理它(或者不要,并观察异常滚滚而来)。

,

你的问题让我有点困惑,所以如果我误解了,我很抱歉。您基本上要问的是 foreach(a,b; [1,4].chunks(2)) 是否可以工作,对吗?

这里的简单解决方案是,如您所说,map 从块到 tuple

import std.typecons : tuple;
import std.algorithm : map;
import std.range : chunks;
import std.stdio : writeln;

unittest {
    pragma(msg,typeof([1,2].chunks(2).front));

    foreach(a,4].chunks(2).map!(a => tuple(a[0],a[1]))) {
        writeln(a,",b);
    }
}
,

在使用 BioTronic 的同时,我尝试编写一些自己的解决方案来解决这个问题(在 DMD 上测试)。我的解决方案适用于切片(但不是固定大小的数组)并避免调用 filter

import std.range : chunks,isInputRange,enumerate;
import std.range : isRandomAccessRange; //changed from "hasSlicing" to "isRandomAccessRange" thanks to BioTronics
import std.traits : isIterable;

/** turns chunks into tuples */
template byTuples(size_t N,M)
if (isRandomAccessRange!M) {   //EDITED
    import std.meta : Repeat;
    import std.typecons : Tuple;
    import std.traits : ForeachType;

    alias VariableGroup = Tuple!(Repeat!(N,ForeachType!M));    //Tuple of N repititions of M's Foreach-iterated Type
    /** turns N consecutive array elements into a Variable Group */
    auto toTuple (Chunk)(Chunk subArray) @nogc @safe pure nothrow
    if (isInputRange!Chunk) {       //Chunk must be indexable
        VariableGroup nextLoopVariables;    //fill the tuple with static foreach loop
        static foreach(index; 0 .. N) {
            static if ( isRandomAccessRange!Chunk ) {  // add cases for other ranges here
                nextLoopVariables[index] = subArray[index];
            } else {
                nextLoopVariables[index] = subArray.popFront();
            }
        }
        return nextLoopVariables;
    }
    /** returns a range of VariableGroups */
    auto byTuples(M array) @safe pure nothrow {
        import std.algorithm.iteration : map;

        static if(!isInputRange!M) {
            static assert(0,"Cannot call map() on fixed-size array.");
//          auto varGroups = array[].chunks(N);     //fixed-size arrays aren't slices by default and cannot be treated like ranges
            //WARNING! invoking "map" on a chunk range from fixed-size array will fail and access wrong memory with no warning or exception despite @safe!
        } else {
            auto varGroups = array.chunks(N);
        }
        //remove last group if incomplete
        if (varGroups.back.length < N) varGroups.popBack();
        //NOTE! I don't know why but `map!toTuple` DOES NOT COMPILE! And will cause a template compilation mess.
        return varGroups.map!(chunk => toTuple(chunk));     //don't know if it uses GC
    }
}

void main() {
    testArrayToTuples([1,4,5,7,9]);
}

// Order of template parameters is relevant.
// You must define parameters implicitly at first to be associated with a template specialization
void testArrayToTuples(U : V[],V)(U arr) {

    double[] randomNumbers = new double[arr.length / 2];
    // generate random numbers
    foreach(i,double x,double y; byTuples!2(arr).enumerate ) {    //cannot use UFCS with "byTuples"
        import std.random : uniform01;
        randomNumbers[i] = (uniform01 * (y - x) + x);
    }
    foreach(n; randomNumbers) { //'n' apparently works despite shadowing a template parameter
        import std.stdio : writeln;
        writeln(n);
    }
}

将元素操作与切片运算符一起使用在这里不起作用,因为 uniform01 中的 uniform01 * (ends[] - starts[]) + starts[] 只会被调用一次而不是多次。

编辑:我还为此代码测试了一些 D 的在线编译器,奇怪的是它们对于相同的代码表现不同。对于 D 的编译,我可以推荐

但那些对我不起作用:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res