Zig 系统编程也能如此简单四:控制流:一切都是表达式

灿飞屋
本章深入讲解Zig语言中控制流的表达式特性,涵盖if/else、switch、while、for、defer、errdefer、break/continue带值、标签块等核心语法。强调所有控制结构均返回值、必须穷尽分支、条件严格为bool、编译期强制资源清理与错误处理,体现Zig'无隐式转换、显式即安全'的设计哲学。

第 4 章 控制流:一切都是表达式

本章目标:掌握 Zig 的控制流。核心心智模型只有一句话——if、switch、块 {}、甚至 while 都能当表达式用,会"求出一个值"。理解这一点,你的 Zig 代码会立刻变得紧凑。


4.1 if:三分身

Zig 的 if 有三种完全不同的用法,新手最容易混淆:

① 普通布尔判断

const std = @import("std");

pub fn main() !void {
    // 注意:这里如果写 main(init: std.process.Init) 却不用 init,
    // 会得到 "unused function parameter" 编译错误 —— main 也不例外!
    const n = try std.fmt.parseInt(i32, "42", 10);

    // 作为语句
    if (n > 0) {
        std.debug.print("正数\n", .{});
    } else if (n < 0) {
        std.debug.print("负数\n", .{});
    } else {
        std.debug.print("零\n", .{});
    }

    // 作为表达式(两个分支类型必须兼容)
    const sign: i32 = if (n > 0) 1 else if (n < 0) -1 else 0;
    std.debug.print("sign = {d}\n", .{sign});
}
[stderr]
正数
sign = 1

⚠️ 条件必须是 bool,不能是"真值"。if (some_pointer)、if (some_int) 都是编译错误。这是 Zig 拒绝隐式转换的一部分。

💡 顺带一个新手必踩的坑:main 的参数也不例外。如果你写了 pub fn main(init: std.process.Init) !void 却没用到 init,编译器会报 unused function parameter。要么改回无参 main(),要么在函数体开头写 _ = init;。本书的示例会在不需要 I/O 时用无参 main(),需要时用 init.io / init.gpa。

② 可选值解包(if (x) |v|)

const std = @import("std");

fn parseAge(s: []const u8) ?u8 {
    return std.fmt.parseInt(u8, s, 10) catch null;
}

pub fn main() !void {
    // 有值时捕获,null 时走 else
    if (parseAge("25")) |age| {
        std.debug.print("年龄 = {d}\n", .{age});
    } else {
        std.debug.print("解析失败\n", .{});
    }

    if (parseAge("abc")) |age| {
        std.debug.print("年龄 = {d}\n", .{age});
    } else {
        std.debug.print("解析失败(走这里)\n", .{});
    }

    // 表达式形式:注意捕获到的是值,不是指针
    const a = if (parseAge("30")) |v| v else 0;
    std.debug.print("a = {d}\n", .{a});

    // 想要指针?用 `|*v|`
    var maybe: ?u8 = 7;
    if (maybe) |*v| {
        v.* = 9; // 直接修改原变量
    }
    std.debug.print("修改后 maybe = {?d}\n", .{maybe});
}
[stderr]
年龄 = 25
解析失败(走这里)
a = 30
修改后 maybe = 9

③ 错误联合解包(if (x) |v| else |e|)

const std = @import("std");

const ParseError = error{ InvalidDigit, Empty };

fn strictParse(s: []const u8) ParseError!u32 {
    if (s.len == 0) return error.Empty;
    var result: u32 = 0;
    for (s) |c| {
        if (c < '0' or c > '9') return error.InvalidDigit;
        result = result * 10 + (c - '0');
    }
    return result;
}

pub fn main() !void {
    // 成功捕获值,失败捕获错误
    if (strictParse("123")) |v| {
        std.debug.print("① 成功 = {d}\n", .{v});
    } else |e| {
        std.debug.print("① 失败 = {s}\n", .{@errorName(e)});
    }

    if (strictParse("12x")) |v| {
        std.debug.print("② 成功 = {d}\n", .{v});
    } else |e| {
        std.debug.print("② 失败 = {s}\n", .{@errorName(e)});
    }

    // 表达式形式
    const value = strictParse("456") catch |e| blk: {
        std.debug.print("(出错 {s},用默认值)\n", .{@errorName(e)});
        break :blk 0;
    };
    std.debug.print("value = {d}\n", .{value});
}
[stderr]
① 成功 = 123
② 失败 = InvalidDigit
value = 456

4.2 switch:必须穷尽,且是表达式

Zig 的 switch 和 C 的完全不同:没有 fallthrough、必须穷尽所有情况、每个分支是一个表达式、整个 switch 也是一个表达式。

const std = @import("std");

const Color = enum { red, green, blue, alpha };
const Value = union(enum) { int: i64, text: []const u8, none };

fn describe(c: Color) []const u8 {
    return switch (c) {
        .red => "红色",
        .green => "绿色",
        .blue => "蓝色",
        .alpha => "透明",
        // 枚举必须全部列出,否则编译错误(除非用 else)
    };
}

fn show(v: Value, arena: std.mem.Allocator) ![]const u8 {
    return switch (v) {
        .int => |n| try arena.print("{d}", .{n}), // 需要分配 -> 传分配器
        .text => |t| t,
        .none => "(无)",
    };
}

pub fn main(init: std.process.Init) !void {
    const arena = init.arena.allocator();

    inline for (.{ Color.red, Color.green, Color.blue, Color.alpha }) |c| {
        std.debug.print("{s} -> {s}\n", .{ @tagName(c), describe(c) });
    }

    // 多值匹配、范围匹配
    const n: i32 = 42;
    const bucket = switch (n) {
        0 => "零",
        1, 2, 3 => "小",
        4...10 => "中", // 闭区间范围
        11...std.math.maxInt(i32) => "大",
        else => "负数",
    };
    std.debug.print("42 -> {s}\n", .{bucket});

    // 捕获载荷(配合 tagged union,见第 6 章)
    const value: Value = .{ .int = 7 };
    std.debug.print("payload -> {s}\n", .{try show(value, arena)});
}
const std = @import("std");

const Op = enum { add, sub, mul, div };

fn apply(comptime op: Op, a: f64, b: f64) f64 {
    return switch (op) {
        .add => a + b,
        .sub => a - b,
        .mul => a * b,
        .div => a / b,
    };
}

pub fn main() !void {
    // inline switch:每个分支生成一份特化代码,op 是编译期常量
    inline for (.{ Op.add, Op.sub, Op.mul, Op.div }) |op| {
        const r = apply(op, 10, 4);
        std.debug.print("{s:>3}(10, 4) = {d}\n", .{ @tagName(op), r });
    }
}
[stderr]
add(10, 4) = 14
sub(10, 4) = 6
mul(10, 4) = 40
div(10, 4) = 2.5

⚠️ @tagName 返回的是 [:0]const u8,可以直接用 {s} 打印。这是调试枚举/tagged union 最好用的函数。


4.3 while:条件、继续表达式、else

Zig 的 while 有一个别的语言没有的东

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灿飞屋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值