- 主题:rust的语法为什么这么丑陋不堪啊?
cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 5, 3, 8, 2, 7};
// 优雅的函数式编程风格
std::ranges::for_each(numbers, [](int n) {
if (n % 2 == 0) {
std::cout << n * n << " ";
}
});
return 0;
}
rust
fn main() {
let numbers = vec![1, 5, 3, 8, 2, 7];
// 必须显式处理迭代器和类型
numbers.iter()
.filter(|&&n| n % 2 == 0)
.map(|&n| n * n)
.for_each(|n| print!("{} ", n));
}
--
FROM 123.113.171.*
不了解rust是不是必须这么写,但是rust支持这个范式很漂亮。
【 在 aiworking 的大作中提到: 】
: cpp
: #include <iostream>
: #include <vector>
: ...................
--
FROM 58.38.48.*
我为数不多的印象中,rust应该不是必须这么写。
【 在 yangtou 的大作中提到: 】
: 不了解rust是不是必须这么写,但是rust支持这个范式很漂亮。
--
FROM 124.127.177.*
使用|x| {}这种语法形式替代显式 lambda 关键字来定义匿名函数,是由C++在C++11 标准中首次引入的。
rust 也是为了尽量接近风格吧
【 在 aiworking 的大作中提到: 】
: cpp
: #include <iostream>
: #include <vector>
: ...................
--
FROM 117.130.205.*
rust这语法真丑陋
--
FROM 171.213.219.*
这是从py学来的,还真不是rust自己原创的。
py应该也是从哪里学来的。
【 在 horkoson 的大作中提到: 】
: rust这语法真丑陋
--
FROM 124.127.177.*
没太看懂,这个例子里,rust里直接 numbers.iter().for_each(...) 不就完事了。
而且这个例子里rust明显更简洁直观。
说到函数式,rust的支持比C++要自然得多,前者是设计之初就考虑到了,后者是通过升级加入功能。
【 在 aiworking 的大作中提到: 】
: cpp
: #include <iostream>
: #include <vector>
: ...................
--
FROM 116.237.207.*
而且“必须显式处理类型”是C++不是rust,你搞反了吧。
【 在 aiworking 的大作中提到: 】
: cpp
: #include <iostream>
: #include <vector>
: ...................
--
FROM 116.237.207.*
链式调用,是从别的语言学的(函数式编程),也不是Rust首创的。
C++也能用链式调用,
1、通过std::ranges的管道符|
std::vector<int> numbers = {1, 5, 3, 8, 2, 7};
for (int n : numbers
| std::views::filter([](int n){ return n % 2 == 0; })
| std::views::transform([](int n){ return n * n; }))
{
std::cout << n << " ";
}
2、通过std::expected或者tl::expected(后者是学的Rust)
tl::expected<int, std::string> parse_int(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return tl::unexpected("not a number");
}
}
int main() {
auto result = parse_int("123")
.map([](int n){ return n * 2; })
.map([](int n){ return n + 1; })
.and_then([](int n){
if (n > 100) return tl::expected<int, std::string>{n};
else return tl::make_unexpected(std::string{"too small"});
});
std::expected<int, std::string> parse_int(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return std::unexpected("not a number");
}
}
int main() {
auto result = parse_int("123")
.transform([](int n){ return n * 2; }) // C++23 用 transform
.transform([](int n){ return n + 1; })
.and_then([](int n){
if (n > 100) return std::expected<int, std::string>{n};
else return std::unexpected("too small");
});
3、自己撸,主要是要求class的每个成员函数最后都返回*this。
--
FROM 61.48.128.*
和py没关系,py还是和cpp比较像的
另外,py更推崇列表推导式
我查了下,这些链式写法最早是函数式编程语言常用的,发扬光大的是jQuery,之后就开始流行于脚本和库中了
【 在 kawolu 的大作中提到: 】
:
: 这是从py学来的,还真不是rust自己原创的。
: py应该也是从哪里学来的。
:
: 【 在 horkoson 的大作中提到: 】
#发自zSMTH@23054RA19C
--
FROM 113.143.104.*