ombre: Improve `range` intrinsic
96f9be70e36717c757066cebc56a2d5858a94877
1 parent
b61f11f2
ombre/src/lisp/evaluator.rs
+21 -18
| 1788 | 1788 | Ok(Expr::Nil) |
|
| 1789 | 1789 | } |
|
| 1790 | 1790 | ||
| 1791 | 1791 | /// Create a list of numbers in a specified range. |
|
| 1792 | 1792 | pub fn range(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1793 | - | match args.as_slice() { |
|
| 1794 | - | [Expr::Integer(end)] => { |
|
| 1795 | - | Ok(Tuple::new((0..*end).map(Expr::Integer).collect::<Vec<_>>()).into()) |
|
| 1796 | - | } |
|
| 1793 | + | let numbers: Vec<_> = match args.as_slice() { |
|
| 1794 | + | [Expr::Integer(end)] => (0..*end).map(Expr::Integer).collect::<Vec<_>>(), |
|
| 1797 | 1795 | [Expr::Integer(start), Expr::Integer(end)] => { |
|
| 1798 | - | Ok(Tuple::new((*start..*end).map(Expr::Integer).collect::<Vec<_>>()).into()) |
|
| 1796 | + | (*start..*end).map(Expr::Integer).collect() |
|
| 1799 | 1797 | } |
|
| 1800 | - | [Expr::Integer(start), Expr::Integer(end), Expr::Integer(step)] => Ok(Tuple::new( |
|
| 1801 | - | (0..) |
|
| 1802 | - | .map(|n| *start + n * *step) |
|
| 1803 | - | .take_while(|&x| x < *end) |
|
| 1804 | - | .map(Expr::Integer) |
|
| 1805 | - | .collect::<Vec<_>>(), |
|
| 1806 | - | ) |
|
| 1807 | - | .into()), |
|
| 1808 | - | _ => Err(Error::WrongArgumentCount { |
|
| 1809 | - | expected: 3, |
|
| 1810 | - | actual: args.len(), |
|
| 1811 | - | }), |
|
| 1812 | - | } |
|
| 1798 | + | [Expr::Integer(start), Expr::Integer(end), Expr::Integer(step)] if start < end => (0..) |
|
| 1799 | + | .map(|n| *start + n * *step) |
|
| 1800 | + | .take_while(|&x| x < *end) |
|
| 1801 | + | .map(Expr::Integer) |
|
| 1802 | + | .collect(), |
|
| 1803 | + | [Expr::Integer(start), Expr::Integer(end), Expr::Integer(step)] if start > end => (0..) |
|
| 1804 | + | .map(|n| *start + n * *step) |
|
| 1805 | + | .take_while(|&x| x > *end) |
|
| 1806 | + | .map(Expr::Integer) |
|
| 1807 | + | .collect(), |
|
| 1808 | + | _ => { |
|
| 1809 | + | return Err(Error::WrongArgumentCount { |
|
| 1810 | + | expected: 3, |
|
| 1811 | + | actual: args.len(), |
|
| 1812 | + | }) |
|
| 1813 | + | } |
|
| 1814 | + | }; |
|
| 1815 | + | Ok(Tuple::new(numbers).into()) |
|
| 1813 | 1816 | } |
|
| 1814 | 1817 | ||
| 1815 | 1818 | /// Greater than. |
|
| 1816 | 1819 | pub fn gt(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1817 | 1820 | ordering(args, |ord| ord.is_gt()) |