added list index function
This commit is contained in:
parent
12caeedf68
commit
fcdde50faa
2 changed files with 48 additions and 0 deletions
|
|
@ -96,6 +96,45 @@ func Len(input *ast.Token, vars ast.VarTable, funcs ast.FuncTable) *ast.Token {
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Takes two arguments
|
||||||
|
* An index and a list
|
||||||
|
* Returns element indexed by index arg
|
||||||
|
* can return nil if index is out of bounds
|
||||||
|
*
|
||||||
|
* Example (index 2 (1 2 3)) -> 2
|
||||||
|
*/
|
||||||
|
func Index(in *ast.Token, vars ast.VarTable, funcs ast.FuncTable) *ast.Token {
|
||||||
|
idx, err := strconv.ParseInt(in.Value(), 10, 64)
|
||||||
|
if err != nil || idx < 0 {
|
||||||
|
log.Log(log.ERR,
|
||||||
|
"index must be a positive integer: " + err.Error(),
|
||||||
|
"index")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
series := in.Next.Expand()
|
||||||
|
iter := &series
|
||||||
|
i := int64(0)
|
||||||
|
for i <= idx {
|
||||||
|
if *iter == nil {
|
||||||
|
log.Log(log.ERR,
|
||||||
|
"index out of bounds",
|
||||||
|
"index")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if i < idx {
|
||||||
|
iter = &((*iter).Next)
|
||||||
|
}
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
ret := (*iter).Copy()
|
||||||
|
ret.Next = nil
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
/* Head
|
/* Head
|
||||||
* Returns first element in the list
|
* Returns first element in the list
|
||||||
* Returns nil if input is not a list or if list is empty
|
* Returns nil if input is not a list or if list is empty
|
||||||
|
|
|
||||||
|
|
@ -72,6 +72,15 @@ func GenFuncTable() ast.FuncTable {
|
||||||
ArgLazy: true,
|
ArgLazy: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"index": &ast.Function{
|
||||||
|
Function: Index,
|
||||||
|
Name: "index",
|
||||||
|
Args: []ast.Token_t{
|
||||||
|
ast.NUMBER,
|
||||||
|
ast.LIST,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
"head": &ast.Function{
|
"head": &ast.Function{
|
||||||
Function: Head,
|
Function: Head,
|
||||||
Name: "head",
|
Name: "head",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue