-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathlambda.rs
More file actions
75 lines (62 loc) · 1.83 KB
/
Copy pathlambda.rs
File metadata and controls
75 lines (62 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::sync::Arc;
use itertools::Itertools;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_utils::aliases::hash_set::HashSet;
use crate::expr::Expression;
use crate::expr::variable::Variable;
/// An expression `body` evaluated with named bindings `params`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Lambda {
params: Arc<Vec<Variable>>,
body: Arc<Expression>,
}
impl Lambda {
/// Create a lambda binding `params` over `body`.
///
/// Returns an error when a parameter name is repeated.
pub fn try_new(
params: impl IntoIterator<Item = impl Into<Variable>>,
body: Expression,
) -> VortexResult<Self> {
let mut vars = Vec::new();
let mut seen = HashSet::new();
for param in params {
let var: Variable = param.into();
if !seen.insert(var.clone()) {
vortex_bail!("duplicate parameter");
}
vars.push(var)
}
Ok(Self {
params: Arc::new(vars),
body: Arc::new(body),
})
}
/// The variables this lambda binds, in declaration order.
pub fn params(&self) -> &[Variable] {
&self.params
}
/// The expression evaluated under the parameter bindings.
pub fn body(&self) -> &Expression {
&self.body
}
}
impl Display for Lambda {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "({}) -> {}", self.params.iter().join(", "), self.body)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn duplicate_parameters_are_rejected() {
assert!(Lambda::try_new(["x", "x"], Expression::Root).is_err());
}
}