小编kro*_*ynx的帖子

在迭代器中找到第一个特定的枚举变体并对其进行转换

我有一个具有不同变体的枚举,我想找到匹配的第一个变体然后通过返回变量值或将其映射到其他变换来变换它.

在Scala中,我会使用case类来执行以下操作:

data.collectFirst{ case d: DataD => d.data }
Run Code Online (Sandbox Code Playgroud)

在Rust中,我必须两次模式匹配才能获得相同的结果.有没有办法让它减少冗长?

enum MyData {
    DataA(String),
    DataB(u64),
    DataC(bool),
    DataD { data: String, val: u32 },
}

fn main() {
    // test data
    let data = vec![
        MyData::DataB(42),
        MyData::DataD {
            data: "meaning of life".to_owned(),
            val: 42,
        },
        MyData::DataC(false),
    ];

    // find first one that matches and map it
    let found: Option<String> = data.iter()
        .find(|d| match **d {
            MyData::DataD { .. } => true,
            _ => false,
        })
        .and_then(|d| match *d {
            MyData::DataD { …
Run Code Online (Sandbox Code Playgroud)

enums vector find rust

4
推荐指数
1
解决办法
340
查看次数

在sml中进行foldl操作

如果有人能在这里指导我,我真的很感激,我真的很想知道我做错了什么,为什么?

这是我的代码:

fun get_longest xs = foldl((fn (x ,y ) => if  String.size x >= String.size y then x
else y),[],xs)
Run Code Online (Sandbox Code Playgroud)

我的函数应该采用字符串列表并返回最长的字符串; 如果列表为空,只是return [].

但是我收到了这个错误:

Error: operator and operand don't agree [tycon mismatch]
  operator domain: 'Z * 'Y -> 'Y
  operand:         (string * string -> string) * int * 'X
  in expression:
  foldl ((fn (<pat>,<pat>) => if <exp> then <exp> else <exp>),0,xs)

uncaught exception Error
  raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
             ../compiler/TopLevel/interact/evalloop.sml:44.55
             ../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
Run Code Online (Sandbox Code Playgroud)

sml

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

AWK中的Substr在Ubuntu中返回空行

我在使用AWK的这条线时遇到问题

apt-cache policy fish | awk '/Candidate/ {print substr($2, 0, 1)}'
Run Code Online (Sandbox Code Playgroud)

在使用Ubuntu的计算机上,18.10我得到了3预期的结果,但是在使用Ubuntu的另一台计算机上,18.04我得到了empty一条代码。

在Ubuntu 18.04中:

j@minimal:~$ apt-cache policy fish | awk '/Candidate/ {print $2}'
2.7.1-3
j@minimal:~$ apt-cache policy fish | awk '/Candidate/ {print substr($2, 0, 1)}'

j@minimal:~$ 
Run Code Online (Sandbox Code Playgroud)

在Ubuntu中 18.10

krono@vulcania:~$ apt-cache policy fish | awk '/Candidate/ {print $2}'
3.0.2-1~cosmic
krono@vulcania:~$ apt-cache policy fish | awk '/Candidate/ {print substr($2, 0, 1)}'
3
krono@vulcania:~$
Run Code Online (Sandbox Code Playgroud)

为什么在Ubuntu 18.04中我得到一个空行而不是2

bash awk

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

标签 统计

awk ×1

bash ×1

enums ×1

find ×1

rust ×1

sml ×1

vector ×1