先把列表反转。
let segments = list.reverse(segments)
然后取第 4 个元素
let chosen = case list.drop(segments, 3) {
[fourth, ..] -> fourth
[] -> ""
}
我还没在本机运行过,不过这样应该可以吧?
更符合习惯的写法如下。
pub fn fourth_from_tail(entries: String) -> Result(String, Nil) {
case list.reverse(string.split(entries, on: "-")) {
// Matches if there are at least 4 segments, binding the 4th from the end to `picked`
[_, _, _, picked, ..] -> Ok(picked)
// Discards strings with fewer than 4 segments
_ -> Error(Nil)
}
}
从英语翻译·查看原文Start by reversing it:
let segments = list.reverse(segments)
then take element number 4
let chosen = case list.drop(segments, 3) {
[fourth, ..] -> fourth
[] -> ""
}
I haven't tried running this locally, but wouldn't this work?
Here's an approach that's more idiomatic:
pub fn fourth_from_tail(entries: String) -> Result(String, Nil) {
case list.reverse(string.split(entries, on: "-")) {
// Matches if there are at least 4 segments, binding the 4th from the end to `picked`
[_, _, _, picked, ..] -> Ok(picked)
// Discards strings with fewer than 4 segments
_ -> Error(Nil)
}
}