implement parens for function calling syntax
This commit is contained in:
55
README.md
55
README.md
@@ -78,42 +78,47 @@ All functions in Lamm are **scoped** similarly to variables. Functions are decla
|
||||
|
||||
```
|
||||
: inc x + x 1
|
||||
inc 24 # => 25
|
||||
(inc 24) # => 25
|
||||
|
||||
:. pythag a b sqrt + ** a 2.0 ** b 2.0
|
||||
pythag 3 4 # => 5
|
||||
(pythag 3 4) # => 5
|
||||
|
||||
:::::. ten'args a b c d e f g h i j
|
||||
[a b c d e f g h i j]
|
||||
```
|
||||
|
||||
The parameter types and return type of functions can be declared using a special syntax unique to function and lambda definitions.
|
||||
Calling a function requires parenthises around the call.
|
||||
|
||||
```
|
||||
# Takes an x of `Any` type
|
||||
: inc x + x 1
|
||||
inc 12 # => 13
|
||||
: inc x
|
||||
+ x 1
|
||||
(inc 12) # => 13
|
||||
|
||||
# Takes an x of `Int` and returns an `Int`
|
||||
: inc ?. x Int -> Int + x 1
|
||||
inc 9 # => 10
|
||||
: inc ?. x Int -> Int
|
||||
+ x 1
|
||||
(inc 9) # => 10
|
||||
```
|
||||
|
||||
The `?.` operator is unique to function declarations and is used to specify the type of an argument. There are also first class functions, here is the syntax for it.
|
||||
|
||||
```
|
||||
# Applies a function to any value
|
||||
:. apply : f x f x
|
||||
apply \sqrt 9 # => 3
|
||||
:. apply : f x
|
||||
(f x)
|
||||
(apply sqrt 9) # => 3
|
||||
|
||||
# Applies a function f which maps an Int to an Int to x
|
||||
:. apply'int ?: f Int -> Int ?. x Int -> Int f x
|
||||
apply'int \sqrt 36 # => 6
|
||||
:. apply'int ?: f Int -> Int ?. x Int -> Int
|
||||
(f x)
|
||||
(apply'int sqrt 36) # => 6
|
||||
```
|
||||
|
||||
The `:` operator inside of a function prototype tells Lamm that this argument must be a function where every argument and it's return type are all `Any`. This means that `: f` is essentially syntactic sugar for `?: f Any -> Any`. Also, in order to pass a function to a function, you must use the `\` operator, which tells Lamm not to call the function.
|
||||
The `:` operator inside of a function prototype tells Lamm that this argument must be a function where every argument and it's return type are all `Any`. This means that `: f` is essentially syntactic sugar for `?: f Any -> Any`. You can pass a function with just it's identifier.
|
||||
|
||||
And off course, `:` and `?:` in function prototypes can also be extended depending on the number of arguments the function must take.
|
||||
And of course, `:` and `?:` in function prototypes can also be extended depending on the number of arguments the function must take.
|
||||
|
||||
## Branching
|
||||
|
||||
@@ -171,28 +176,28 @@ Using these, you can build a lot of fundamental functional paradigm functions.
|
||||
|
||||
```
|
||||
:. map : f ?. x [] -> []
|
||||
?? bool x
|
||||
+ f head x map \f tail x
|
||||
empty
|
||||
map ;x ** x 2 [1 2 3 4 5 6 7 8 9 10] # => [1 4 9 16 25 36 49 64 81 100]
|
||||
?? bool x
|
||||
[+ (f head x) (map f tail x)
|
||||
empty
|
||||
(map ;x ** x 2 [1 2 3 4 5 6 7 8 9 10]) # => [1 4 9 16 25 36 49 64 81 100]
|
||||
|
||||
:: iterate : f i count -> []
|
||||
?? > count 0
|
||||
+ i iterate \f f i - count 1
|
||||
empty
|
||||
iterate (+ 1) 0 10 # => [0 1 2 3 4 5 6 7 8 9]
|
||||
?? > count 0
|
||||
[+ i (iterate f (f i) - count 1)
|
||||
empty
|
||||
(iterate (+ 1) 0 10) # => [0 1 2 3 4 5 6 7 8 9]
|
||||
|
||||
:. take ?. n Int ?. x [] -> []
|
||||
?? > n 0
|
||||
+ head x take - n 1 tail x
|
||||
[+ head x (take - n 1 tail x)
|
||||
empty
|
||||
take 3 [1 2 3 4 5] # => [1 2 3]
|
||||
(take 3 [1 2 3 4 5]) # => [1 2 3]
|
||||
|
||||
:. take'while ?: pred Any -> Bool ?. x [] -> []
|
||||
?? && bool x pred head x
|
||||
+ head x take'while \pred tail x
|
||||
?? && bool x (pred head x)
|
||||
[+ head x (take'while pred tail x)
|
||||
empty
|
||||
take'while (> 10) [1 3 5 7 9 11 13 15 16] # => [1 3 5 7 9]
|
||||
(take'while (> 10) [1 3 5 7 9 11 13 15 16]) # => [1 3 5 7 9]
|
||||
```
|
||||
|
||||
## Lambdas
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::error::Error;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::iter::Peekable;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum ParseTree {
|
||||
@@ -176,40 +177,7 @@ impl Parser {
|
||||
|
||||
match token.token() {
|
||||
TokenType::Constant(c) => Ok(Some(ParseTree::Value(c))),
|
||||
TokenType::Identifier(ident) => {
|
||||
match self.get_object_type(&ident).ok_or(
|
||||
Error::new(format!("undefined identifier {ident}"))
|
||||
.location(token.line, token.location))? {
|
||||
Type::Function(f) => {
|
||||
let f = f.clone();
|
||||
let args = self.get_args(tokens, f.1.len())?;
|
||||
|
||||
if args.len() < f.1.len() {
|
||||
let mut counter = 0;
|
||||
let func_args: Vec<Type> = f.1.iter().skip(args.len()).cloned().collect();
|
||||
let (names, types): (Vec<String>, Vec<Type>) = func_args
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
counter += 1;
|
||||
(format!("{counter}"), t)
|
||||
}).unzip();
|
||||
let function_type = FunctionType(f.0.clone(), types);
|
||||
|
||||
Ok(Some(ParseTree::Value(Value::Function(Function::lambda(
|
||||
function_type,
|
||||
names.clone(),
|
||||
Box::new(ParseTree::FunctionCall(ident,
|
||||
vec![
|
||||
args,
|
||||
names.into_iter().map(|x| ParseTree::Variable(x)).collect()
|
||||
].concat())))))))
|
||||
} else {
|
||||
Ok(Some(ParseTree::FunctionCall(ident, args)))
|
||||
}
|
||||
}
|
||||
_ => Ok(Some(ParseTree::Variable(ident))),
|
||||
}
|
||||
},
|
||||
TokenType::Identifier(ident) => Ok(Some(ParseTree::Variable(ident))),
|
||||
TokenType::Operator(op) => match op {
|
||||
Op::OpenArray => {
|
||||
let mut depth = 1;
|
||||
@@ -253,7 +221,7 @@ impl Parser {
|
||||
|
||||
// take tokens until we reach the end of this array
|
||||
// if we don't collect them here it causes rust to overflow computing the types
|
||||
let array_tokens = tokens.by_ref().take_while(|t| match t {
|
||||
let tokens = tokens.by_ref().take_while(|t| match t {
|
||||
Ok(t) => match t.token() {
|
||||
TokenType::Operator(Op::OpenStatement) => {
|
||||
depth += 1;
|
||||
@@ -268,22 +236,59 @@ impl Parser {
|
||||
_ => true,
|
||||
}).collect::<Result<Vec<_>, Error>>()?;
|
||||
|
||||
let array_tokens = array_tokens
|
||||
let mut tokens = tokens
|
||||
.into_iter()
|
||||
.map(|t| Ok(t))
|
||||
.collect::<Vec<Result<Token, Error>>>()
|
||||
.into_iter()
|
||||
.peekable();
|
||||
|
||||
let trees: Vec<ParseTree> = self.clone().trees(array_tokens)
|
||||
.collect::<Result<_, Error>>()?;
|
||||
if let Some(Ok(Some(Type::Function(f)))) = tokens.peek()
|
||||
.map(|t| t.clone().and_then(|t| match t.token() {
|
||||
TokenType::Identifier(ident) =>
|
||||
Ok(Some(self.get_object_type(&ident).ok_or(
|
||||
Error::new(format!("undefined identifier {ident}"))
|
||||
.location(token.line, token.location))?)),
|
||||
_ => Ok(None),
|
||||
}))
|
||||
{
|
||||
let token = tokens.next().unwrap().unwrap();
|
||||
let params: Vec<ParseTree> = self.clone().trees(tokens).collect::<Result<_, Error>>()?;
|
||||
|
||||
let tree = trees.into_iter().fold(
|
||||
ParseTree::Nop,
|
||||
|acc, x| ParseTree::Operator(Op::Compose, vec![acc, x.clone()]),
|
||||
);
|
||||
match params.len().cmp(&f.1.len()) {
|
||||
Ordering::Equal => Ok(Some(ParseTree::FunctionCall(token.lexeme, params))),
|
||||
Ordering::Greater => Err(Error::new(format!("too many arguments to {}", token.lexeme)).location(token.line, token.location)),
|
||||
Ordering::Less => {
|
||||
let mut counter = 0;
|
||||
let func_args: Vec<Type> = f.1.iter().skip(params.len()).cloned().collect();
|
||||
let (names, types): (Vec<String>, Vec<Type>) = func_args
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
counter += 1;
|
||||
(format!("{counter}"), t)
|
||||
}).unzip();
|
||||
let function_type = FunctionType(f.0.clone(), types);
|
||||
|
||||
Ok(Some(ParseTree::Value(Value::Function(Function::lambda(
|
||||
function_type,
|
||||
names.clone(),
|
||||
Box::new(ParseTree::FunctionCall(token.lexeme,
|
||||
vec![
|
||||
params,
|
||||
names.into_iter().map(|x| ParseTree::Variable(x)).collect()
|
||||
].concat())))))))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let trees: Vec<ParseTree> = self.clone().trees(tokens).collect::<Result<_, Error>>()?;
|
||||
|
||||
Ok(Some(tree))
|
||||
let tree = trees.into_iter().fold(
|
||||
ParseTree::Nop,
|
||||
|acc, x| ParseTree::Operator(Op::Compose, vec![acc, x.clone()]),
|
||||
);
|
||||
|
||||
Ok(Some(tree))
|
||||
}
|
||||
},
|
||||
Op::Equ => {
|
||||
let token = tokens.next()
|
||||
@@ -361,10 +366,6 @@ impl Parser {
|
||||
},
|
||||
Op::LambdaDefine(arg_count) => Ok(Some(ParseTree::LambdaDefinition(self.parse_lambda_definition(tokens, arg_count)?))),
|
||||
Op::Empty => Ok(Some(ParseTree::Value(Value::Array(Type::Any, vec![])))),
|
||||
Op::NonCall => {
|
||||
let name = Self::get_identifier(tokens.next())?;
|
||||
Ok(Some(ParseTree::NonCall(name)))
|
||||
},
|
||||
Op::If => {
|
||||
let cond = self.parse(tokens)?
|
||||
.ok_or(Error::new("? statement requires a condition".into())
|
||||
|
||||
@@ -59,7 +59,6 @@ pub enum Op {
|
||||
Init,
|
||||
Fini,
|
||||
Export,
|
||||
NonCall,
|
||||
}
|
||||
|
||||
impl fmt::Display for Op {
|
||||
@@ -112,7 +111,6 @@ impl fmt::Display for Op {
|
||||
Op::Init => "init",
|
||||
Op::Fini => "fini",
|
||||
Op::Export => "export",
|
||||
Op::NonCall => "\\",
|
||||
};
|
||||
|
||||
write!(f, "{s}")
|
||||
@@ -281,7 +279,6 @@ impl<R: BufRead> Tokenizer<R> {
|
||||
("!", Op::Not),
|
||||
("&&", Op::And),
|
||||
("||", Op::Or),
|
||||
("\\", Op::NonCall),
|
||||
]);
|
||||
|
||||
let c = if let Some(c) = self.next_char() {
|
||||
|
||||
Reference in New Issue
Block a user