Documentation ¶
Index ¶
- Variables
- type ActiveRecord
- type BaseObject
- func (o *BaseObject) AddMethod(fn *BuiltinFunction)
- func (o *BaseObject) AsBool() bool
- func (o *BaseObject) AsInterface() any
- func (o *BaseObject) AsRepr() string
- func (o *BaseObject) AsString() string
- func (o *BaseObject) Docs() string
- func (o *BaseObject) GetProperty(name string) Object
- func (o *BaseObject) Id() string
- func (o *BaseObject) OnIndex(scope *Scope, t *Tuple) Object
- func (o *BaseObject) OnIndexAssign(scope *Scope, t *Tuple, value Object) Object
- func (o *BaseObject) OnOperator(scope *Scope, op string, right Object) Object
- func (o *BaseObject) Parent() Object
- func (o *BaseObject) SetDocs(docs string)
- func (o *BaseObject) SetParent(p Object)
- func (o *BaseObject) SetProperty(name string, value Object)
- func (o *BaseObject) Type() ObjectType
- func (o *BaseObject) TypeId() TypeIdentifier
- type BaseObjectType
- type Boolean
- type BooleanType
- type BuiltinFn
- type BuiltinFunction
- func (o *BuiltinFunction) AsBool() bool
- func (o *BuiltinFunction) AsInterface() any
- func (o *BuiltinFunction) AsRepr() string
- func (o *BuiltinFunction) AsString() string
- func (o *BuiltinFunction) Call(scope *Scope, args ...Object) Object
- func (o *BuiltinFunction) Check(scope *Scope, args ...Object) Object
- func (o *BuiltinFunction) WithDocs(d string) *BuiltinFunction
- func (o *BuiltinFunction) WithSignature(params ...*Param) *BuiltinFunction
- type Data
- type DataType
- type Dict
- type DictType
- type Error
- type ErrorType
- type Evaluator
- type Function
- type FunctionType
- type Interruption
- func (i *Interruption) AsBool() bool
- func (i *Interruption) AsString() string
- func (i *Interruption) Docs() string
- func (i *Interruption) GetProperty(string) Object
- func (i *Interruption) Id() string
- func (i *Interruption) SetDocs(string)
- func (i *Interruption) SetProperty(string, Object)
- func (i *Interruption) Type() ObjectType
- func (i *Interruption) TypeId() TypeIdentifier
- type InterruptionType
- type List
- type ListType
- type Maybe
- type MaybeType
- type ModuleType
- type Number
- type NumberType
- type Object
- type ObjectType
- type Param
- type Runner
- type Scope
- func (s *Scope) ActiveRecord() ActiveRecord
- func (s *Scope) Depth() int
- func (s *Scope) Eval() Evaluator
- func (s *Scope) GetGlobal(name string) Object
- func (s *Scope) GetLocal(name string) Object
- func (s *Scope) Interrupt(interruption *Interruption) Object
- func (s *Scope) Keys() []string
- func (s *Scope) New() *Scope
- func (s *Scope) Parent() *Scope
- func (s *Scope) PopNode() ast.Node
- func (s *Scope) Print(name string)
- func (s *Scope) PushNode(node ast.Node)
- func (s *Scope) Runner() Runner
- func (s *Scope) SetActiveRecord(ar ActiveRecord)
- func (s *Scope) SetGlobal(name string, obj Object)
- func (s *Scope) SetLocal(name string, obj Object)
- func (s *Scope) WithEval(eval Evaluator) *Scope
- type Stream
- type StreamIteration
- func (i *StreamIteration) AsBool() bool
- func (i *StreamIteration) AsString() string
- func (i *StreamIteration) Docs() string
- func (i *StreamIteration) GetProperty(string) Object
- func (i *StreamIteration) Id() string
- func (i *StreamIteration) SetDocs(string)
- func (i *StreamIteration) SetProperty(string, Object)
- func (i *StreamIteration) Type() ObjectType
- func (i *StreamIteration) TypeId() TypeIdentifier
- type StreamType
- type String
- type StringType
- type Tuple
- type TupleType
- type Type
- type TypeIdentifier
- type ValidationFn
- type Validator
Constants ¶
This section is empty.
Variables ¶
var BooleanId = TypeIdentifier("Boolean")
var BooleanTypeObj = NewBooleanType()
var Count = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) count := 0 for { maybe := Stream_Next.Call(scope, stream) if isRaise(maybe) { return maybe } if stream.Finished { return NewNumber(float64(count)) } count++ } }, `count`, `Counts the stream.`, P("stream"), )
var CountBy = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) f := args[1].(*Function) count := 0 for { maybe := Stream_Next.Call(scope, stream) if isRaise(maybe) { return maybe } if stream.Finished { return NewNumber(float64(count)) } value := maybe.(*Maybe).Value ret := scope.Eval().Call(scope, f, toLambdaParams(value)) if isRaise(ret) { return ret } number, ok := ret.(*Number) if !ok { return scope.Interrupt(Raise("expected number, got %s", value.Type())) } count += int(number.Value) } }, `countBy`, `Counts the stream.`, P("stream"), P("f", V.Type(FunctionId)), )
var DataId = TypeIdentifier("Data")
var DictId = TypeIdentifier("Dict")
var DictTypeObj = NewDictType()
var Dict_Clear = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) this.Elements = make(map[string]Object) return this }, `Clear`, `Removes all elements from the dictionary.`, P("this", V.Type(DictId)), )
var Dict_Concat = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) others := args[1:] elements := this.Elements for _, other := range others { for k, v := range other.(*Dict).Elements { elements[k] = v } } return NewDict(elements) }, `Concat`, `Returns a new dictionary with the elements of both dictionaries.`, P("this", V.Type(DictId)), P("other", V.Type(DictId)).AsSpread(), )
var Dict_Contains = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) element := args[1] for _, v := range this.Elements { if scope.eval.Operator(scope, "==", v, element).AsBool() { return True } } return False }, `Contains`, `Returns true if the specified element exists in the dictionary.`, P("this", V.Type(DictId)), P("element"), )
var Dict_ContainsFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) f := args[1] for k, v := range this.Elements { if scope.eval.Call(scope, f, []Object{v, NewString(k)}).AsBool() { return True } } return False }, `ContainsFn`, `Returns true if the specified function returns true for any element in the dictionary.`, P("this", V.Type(DictId)), P("f", V.Type(FunctionId)), )
var Dict_Copy = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) elements := make(map[string]Object) for k, v := range this.Elements { elements[k] = v } return NewDict(elements) }, `Copy`, `Returns a copy of the dictionary.`, P("this", V.Type(DictId)), )
var Dict_Count = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) elements := args[1:] var count int for _, v := range this.Elements { for _, element := range elements { if scope.eval.Operator(scope, "==", v, element).AsBool() { count++ } } } return NewNumber(float64(count)) }, `Count`, `Returns the number of elements that match the specified element.`, P("this", V.Type(DictId)), P("element").AsSpread(), )
var Dict_CountFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) f := args[1] var count int for k, v := range this.Elements { if scope.eval.Call(scope, f, []Object{v, NewString(k)}).AsBool() { count++ } } return NewNumber(float64(count)) }, `CountFn`, `Returns the number of elements that match the specified function.`, P("this", V.Type(DictId)), P("f", V.Type(FunctionId)), )
var Dict_Elements = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) keys := []string{} for k := range this.Elements { keys = append(keys, k) } idx := 0 return NewInternalStream(func(s *Scope) Object { if idx >= len(keys) { return nil } k := keys[idx] idx++ return YieldWith(NewTuple(this.Elements[k], NewString(k))) }, scope) }, `Elements`, `Returns a stream of all key-value pairs in the dictionary.`, P("this", V.Type(DictId)), )
var Dict_Find = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) elements := args[1:] for k, v := range this.Elements { for _, element := range elements { if scope.eval.Operator(scope, "==", v, element).AsBool() { return NewString(k) } } } return False }, `Find`, `Returns the key of the first element that matches the specified element.`, P("this", V.Type(DictId)), P("element").AsSpread(), )
var Dict_FindAll = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) elements := args[1:] var keys []Object for k, v := range this.Elements { for _, element := range elements { if scope.eval.Operator(scope, "==", v, element).AsBool() { keys = append(keys, NewString(k)) } } } return NewList(keys...) }, `FindAll`, `Returns the keys of all elements that match the specified element.`, P("this", V.Type(DictId)), P("element").AsSpread(), )
var Dict_FindAllFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) f := args[1] var keys []Object for k, v := range this.Elements { ko := NewString(k) if scope.eval.Call(scope, f, []Object{v, ko}).AsBool() { keys = append(keys, ko) } } return NewList(keys...) }, `FindAllFn`, `Returns the keys of all elements that match the specified function.`, P("this", V.Type(DictId)), P("f", V.Type(FunctionId)), )
var Dict_FindFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) f := args[1] for k, v := range this.Elements { ko := NewString(k) if scope.eval.Call(scope, f, []Object{v, ko}).AsBool() { return ko } } return False }, `FindFn`, `Returns the key of the first element that matches the specified function.`, P("this", V.Type(DictId)), P("f", V.Type(FunctionId)), )
var Dict_Get = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) index := args[1] res, ok := this.Elements[index.AsString()] if !ok { return scope.Interrupt(Raise("key not found: %s", index.AsString())) } return res }, `Get`, `Gets the element at the specified index.`, P("this", V.Type(DictId)), P("index"), )
var Dict_GetOr = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) index := args[1] def := args[2] res, ok := this.Elements[index.AsString()] if !ok { return def } return res }, `GetOr`, `Gets the element at the specified index or returns the default value.`, P("this", V.Type(DictId)), P("index"), P("default"), )
var Dict_Has = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) index := args[1] _, ok := this.Elements[index.AsString()] return NewBoolean(ok) }, `Has`, `Returns true if the specified index exists in the dictionary.`, P("this", V.Type(DictId)), P("index"), )
var Dict_IsEmpty = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) return NewBoolean(len(this.Elements) == 0) }, `IsEmpty`, `Returns true if the dictionary is empty.`, )
var Dict_Items = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) var items []Object for k, v := range this.Elements { items = append(items, NewList(NewString(k), v)) } return NewList(items...) }, `Items`, `Returns a list of all key-value pairs in the dictionary.`, P("this", V.Type(DictId)), )
var Dict_Keys = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) var keys []Object for k := range this.Elements { keys = append(keys, NewString(k)) } return NewList(keys...) }, `Keys`, `Returns a list of all keys in the dictionary.`, P("this", V.Type(DictId)), )
var Dict_Remove = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) index := args[1] res, ok := this.Elements[index.AsString()] if !ok { return scope.Interrupt(Raise("key not found: %s", index.AsString())) } delete(this.Elements, index.AsString()) return res }, `Remove`, `Removes the element at the specified index.`, P("this", V.Type(DictId)), P("index"), )
var Dict_Set = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) index := args[1] this.Elements[index.AsString()] = args[2] return this }, `Set`, `Sets the element at the specified index.`, P("this", V.Type(DictId)), P("index"), P("element"), )
var Dict_Size = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) return NewNumber(float64(len(this.Elements))) }, `Size`, `Returns the number of elements in the dictionary.`, P("this", V.Type(DictId)), )
var Dict_Values = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Dict) var values []Object for _, v := range this.Elements { values = append(values, v) } return NewList(values...) }, `Values`, `Returns a list of all values in the dictionary.`, P("this", V.Type(DictId)), )
var Each = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) f := args[1].(*Function) return NewInternalStream(func(s *Scope) Object { maybe := Stream_Next.Call(s, stream) if isRaise(maybe) { return maybe } if stream.Finished { return nil } value := maybe.(*Maybe).Value ret := scope.Eval().Call(scope, f, toLambdaParams(value)) if isRaise(ret) { return ret } return YieldWith(value) }, scope) }, `each`, `Iterates over the stream.`, P("stream"), P("f", V.Type(FunctionId)), )
var EmptyError = NewErrorFromString("Value is empty.")
var EmptyString = NewString("")
var ErrorId = TypeIdentifier("Error")
var ErrorTypeObj = NewErrorType()
var Error_Msg = NewBuiltinFunction("Msg", func(scope *Scope, args ...Object) Object { this := args[0].(*Error) return NewString(this.Message) })
---------------------------------------------------------------------------- Instance Methods ----------------------------------------------------------------------------
var False = internalBoolean(false)
var Filter = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) f := args[1].(*Function) return NewInternalStream(func(s *Scope) Object { for { maybe := Stream_Next.Call(s, stream) if isRaise(maybe) { return maybe } if stream.Finished { return nil } value := maybe.(*Maybe).Value ret := scope.Eval().Call(scope, f, toLambdaParams(value)) if isRaise(ret) { return ret } if ret.AsBool() { return YieldWith(value) } } }, scope) }, `filter`, `Filters the stream.`, P("stream"), P("f", V.Type(FunctionId)), )
var FunctionId = TypeIdentifier("Function")
var FunctionTypeObj = NewFunctionType()
var ListId = TypeIdentifier("List")
var ListTypeObj = NewListType()
var List_Clear = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) this.Elements = this.Elements[:0] return this }, `Clear`, `Removes all elements from the list.`, P("this", V.Type(ListId)), )
var List_Concat = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) others := args[1:] e := this.Elements for _, other := range others { e = append(e, other.(*List).Elements...) } return NewList(e...) }, `Concat`, `Concatenates the list with one or more other lists.`, P("this", V.Type(ListId)), P("others", V.Type(ListId)).AsSpread(), )
var List_Contains = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) target := args[1] for _, e := range this.Elements { ret := scope.Eval().Operator(scope, "==", e, target) if isRaise(ret) { return ret } else if ret.AsBool() { return True } } return False }, `Contains`, `Returns true if the list contains the specified element.`, P("this", V.Type(ListId)), P("element"), )
var List_ContainsFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) for _, e := range this.Elements { ret := scope.Eval().Call(scope, f, []Object{e}) if isRaise(ret) { return ret } else if ret.AsBool() { return True } } return False }, `ContainsFn`, `Returns true if the list contains an element that satisfies the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_Copy = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) elements := make([]Object, len(this.Elements)) copy(elements, this.Elements) return NewList(elements...) }, `Copy`, `Returns a shallow copy of the list.`, P("this", V.Type(ListId)), )
var List_Count = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) targets := args[1:] count := 0 for _, e := range this.Elements { for _, target := range targets { ret := scope.Eval().Operator(scope, "==", e, target) if isRaise(ret) { return ret } else if ret.AsBool() { count++ break } } } return NewNumber(float64(count)) }, `Count`, `Returns the number of occurrences of any of the specified elements in the list.`, P("this", V.Type(ListId)), P("targets").AsSpread(), )
var List_CountFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) count := 0 for _, e := range this.Elements { ret := scope.Eval().Call(scope, f, []Object{e}) if isRaise(ret) { return ret } else if ret.AsBool() { count++ } } return NewNumber(float64(count)) }, `CountFn`, `Returns the number of elements that satisfy the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_Elements = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) idx := 0 return NewInternalStream(func(s *Scope) Object { if idx >= len(this.Elements) { return nil } e := this.Elements[idx] idx++ return YieldWith(NewTuple(e, NewNumber(float64(idx-1)))) }, scope) }, `Elements`, `Returns a stream of the elements in the list.`, P("this", V.Type(ListId)), )
---------------------------------------------------------------------------- Stream ----------------------------------------------------------------------------
var List_Find = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) targets := args[1:] for i, e := range this.Elements { for _, target := range targets { ret := scope.Eval().Operator(scope, "==", e, target) if isRaise(ret) { return ret } else if ret.AsBool() { return NewNumber(float64(i)) } } } return MinusOne }, `Find`, `Returns the index of the first occurrence of any of the specified elements in the list.`, P("this", V.Type(ListId)), P("targets").AsSpread(), )
var List_FindAll = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) targets := args[1:] result := NewList() for i, e := range this.Elements { for _, target := range targets { ret := scope.Eval().Operator(scope, "==", e, target) if isRaise(ret) { return ret } else if ret.AsBool() { result.Elements = append(result.Elements, NewNumber(float64(i))) break } } } return result }, `FindAll`, `Returns the indices of all occurrences of any of the specified elements in the list.`, P("this", V.Type(ListId)), P("targets").AsSpread(), )
var List_FindAllFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) result := NewList() for i, e := range this.Elements { ret := scope.Eval().Call(scope, f, []Object{e, NewNumber(float64(i))}) if isRaise(ret) { return ret } else if ret.AsBool() { result.Elements = append(result.Elements, NewNumber(float64(i))) } } return result }, `FindAllFn`, `Returns the indices of all elements that satisfy the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_FindFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) for i, e := range this.Elements { ret := scope.Eval().Call(scope, f, []Object{e, NewNumber(float64(i))}) if isRaise(ret) { return ret } else if ret.AsBool() { return NewNumber(float64(i)) } } return MinusOne }, `FindFn`, `Returns the index of the first element that satisfies the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_FindLast = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) targets := args[1:] for i := len(this.Elements) - 1; i >= 0; i-- { e := this.Elements[i] for _, target := range targets { ret := scope.Eval().Operator(scope, "==", e, target) if isRaise(ret) { return ret } else if ret.AsBool() { return NewNumber(float64(i)) } } } return MinusOne }, `FindLast`, `Returns the index of the last occurrence of any of the specified elements in the list.`, P("this", V.Type(ListId)), P("targets").AsSpread(), )
var List_FindLastFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) for i := len(this.Elements) - 1; i >= 0; i-- { e := this.Elements[i] ret := scope.Eval().Call(scope, f, []Object{e, NewNumber(float64(i))}) if isRaise(ret) { return ret } else if ret.AsBool() { return NewNumber(float64(i)) } } return MinusOne }, `FindLastFn`, `Returns the index of the last element that satisfies the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_Get = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) index := int(args[1].(*Number).Value) len := len(this.Elements) if index < 0 { index = len + index } if index < 0 || index >= len { return scope.Interrupt(Raise("index out of range")) } return this.Elements[index] }, `Get`, `Returns the element at the specified index.`, P("this", V.Type(ListId)), P("index", V.Type(NumberId)), )
---------------------------------------------------------------------------- Indexing and Search ----------------------------------------------------------------------------
var List_GetOr = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) index := int(args[1].(*Number).Value) len := len(this.Elements) if index < 0 { index = len + index } if index < 0 || index >= len { return args[2] } return this.Elements[index] }, `GetOr`, `Returns the element at the specified index or the default value if the index is out of range.`, P("this", V.Type(ListId)), P("index", V.Type(NumberId)), P("default"), )
var List_Insert = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) index := int(args[1].(*Number).Value) element := args[2] len := len(this.Elements) if index < 0 { index = len + index } if index < 0 || index > len { return scope.Interrupt(Raise("index out of range")) } this.Elements = append(this.Elements[:index], append([]Object{element}, this.Elements[index:]...)...) return this }, `Insert`, `Inserts an element at the specified index.`, P("this", V.Type(ListId)), P("index", V.Type(NumberId)), P("element"), )
var List_IsEmpty = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) return NewBoolean(len(this.Elements) == 0) }, `IsEmpty`, `Returns true if the list is empty.`, P("this", V.Type(ListId)), )
var List_Join = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) sep := args[1].(*String).Value var elements []string for _, e := range this.Elements { elements = append(elements, e.AsString()) } return NewString(strings.Join(elements, sep)) }, `Join`, `Concatenates the elements of the list into a single string using the specified separator.`, P("this", V.Type(ListId)), P("separator", V.Type(StringId)), )
---------------------------------------------------------------------------- Formatter ----------------------------------------------------------------------------
var List_Pop = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) if len(this.Elements) == 0 { return scope.Interrupt(Raise("cannot pop from an empty list")) } last := this.Elements[len(this.Elements)-1] this.Elements = this.Elements[:len(this.Elements)-1] return last }, `Pop`, `Removes the last element from the list and returns it.`, P("this", V.Type(ListId)), )
var List_Push = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) this.Elements = append(this.Elements, args[1]) return this }, `Push`, `Appends an element to the end of the list.`, P("this", V.Type(ListId)), P("element"), )
var List_Remove = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) element := args[1] for i, e := range this.Elements { if scope.Eval().Operator(scope, "==", e, element) == True { this.Elements = append(this.Elements[:i], this.Elements[i+1:]...) return this } } return scope.Interrupt(Raise("element not found")) }, `Remove`, `Removes the first occurrence of the specified element from the list.`, P("this", V.Type(ListId)), P("element"), )
var List_RemoveAt = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) index := int(args[1].(*Number).Value) len := len(this.Elements) if index < 0 { index = len + index } if index < 0 || index >= len { return scope.Interrupt(Raise("index out of range")) } this.Elements = append(this.Elements[:index], this.Elements[index+1:]...) return this }, `RemoveAt`, `Removes the element at the specified index.`, P("this", V.Type(ListId)), P("index", V.Type(NumberId)), )
var List_Reverse = F( func(scope *Scope, args ...Object) Object { copy := List_Copy.Call(scope, args[0]) if isRaise(copy) { return copy } return List_Reversed.Call(scope, copy) }, `Reverse`, `Copy and reverses the order of the elements in the new list.`, P("this", V.Type(ListId)), )
var List_Reversed = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) for i, j := 0, len(this.Elements)-1; i < j; i, j = i+1, j-1 { this.Elements[i], this.Elements[j] = this.Elements[j], this.Elements[i] } return this }, `Reversed`, `Reverses the order of the elements in the list.`, P("this", V.Type(ListId)), )
var List_Set = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) index := int(args[1].(*Number).Value) len := len(this.Elements) if index < 0 { index = len + index } if index < 0 || index >= len { return scope.Interrupt(Raise("index out of range")) } this.Elements[index] = args[2] return this }, `Set`, `Sets the element at the specified index.`, P("this", V.Type(ListId)), P("index", V.Type(NumberId)), P("element"), )
---------------------------------------------------------------------------- Add/Remove ----------------------------------------------------------------------------
var List_Size = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) return NewNumber(float64(len(this.Elements))) }, `Size`, `Returns the number of elements in the list.`, P("this", V.Type(ListId)), )
---------------------------------------------------------------------------- Checkers ----------------------------------------------------------------------------
var List_Sort = F( func(scope *Scope, args ...Object) Object { copy := List_Copy.Call(scope, args[0]) if isRaise(copy) { return copy } return List_Sorted.Call(scope, copy) }, `Sort`, `Copy and sorts the new list in ascending order.`, P("this", V.Type(ListId)), )
var List_SortFn = F( func(scope *Scope, args ...Object) Object { copy := List_Copy.Call(scope, args[0]) if isRaise(copy) { return copy } return List_SortedFn.Call(scope, copy, args[1]) }, `SortFn`, `Copy and sorts the new list based on the result of the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_Sorted = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) sort.Slice(this.Elements, func(i, j int) bool { ret := scope.Eval().Operator(scope, "<", this.Elements[i], this.Elements[j]) if isRaise(ret) { return false } return ret.AsBool() }) return this }, `Sorted`, `Sorts the list in ascending order.`, P("this", V.Type(ListId)), )
---------------------------------------------------------------------------- Ordering ----------------------------------------------------------------------------
var List_SortedFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) sort.Slice(this.Elements, func(i, j int) bool { ret := scope.Eval().Call(scope, f, []Object{this.Elements[i], this.Elements[j]}) if isRaise(ret) { return false } return ret.AsBool() }) return this }, `SortedFn`, `Sorts the list based on the result of the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_Split = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) separator := args[1] result := NewList() sublist := NewList() for _, e := range this.Elements { if scope.Eval().Operator(scope, "==", e, separator) == True { result.Elements = append(result.Elements, sublist) sublist = NewList() } else { sublist.Elements = append(sublist.Elements, e) } } result.Elements = append(result.Elements, sublist) return result }, `Split`, `Splits the list into sublists based on the separator.`, P("this", V.Type(ListId)), P("separator"), )
var List_SplitAt = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) index := int(args[1].(*Number).Value) len := len(this.Elements) if index < 0 { index = len + index } if index < 0 || index >= len { return scope.Interrupt(Raise("index out of range")) } return NewList(NewList(this.Elements[:index]...), NewList(this.Elements[index:]...)) }, `SplitAt`, `Splits the list into two sublists at the specified index.`, P("this", V.Type(ListId)), P("index", V.Type(NumberId)), )
var List_SplitFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) f := args[1].(*Function) result := NewList() sublist := NewList() for i, e := range this.Elements { ret := scope.Eval().Call(scope, f, []Object{e, NewNumber(float64(i))}) if isRaise(ret) { return ret } if ret.AsBool() { result.Elements = append(result.Elements, sublist) sublist = NewList() } sublist.Elements = append(sublist.Elements, e) } if len(sublist.Elements) > 0 { result.Elements = append(result.Elements, sublist) } return result }, `SplitFn`, `Splits the list into sublists based on the result of the function.`, P("this", V.Type(ListId)), P("f", V.Type(FunctionId)), )
var List_Sub = F( func(scope *Scope, args ...Object) Object { this := args[0].(*List) from := int(args[1].(*Number).Value) to := int(args[2].(*Number).Value) len := len(this.Elements) if from < 0 { from = len + from } if to < 0 { to = len + to } if to < from || to < 0 || from >= len { return NewList() } from = max(0, from) to = min(len, to) return NewList(this.Elements[from:to]...) }, `Sub`, `Returns a new list containing the elements from the start index to the end index.`, P("this", V.Type(ListId)), P("start", V.Type(NumberId)), P("end", V.Type(NumberId)), )
var Map = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) f := args[1].(*Function) return NewInternalStream(func(s *Scope) Object { maybe := Stream_Next.Call(s, stream) if isRaise(maybe) { return maybe } if stream.Finished { return nil } value := maybe.(*Maybe).Value ret := scope.Eval().Call(scope, f, toLambdaParams(value)) if isRaise(ret) { return ret } return YieldWith(ret) }, scope) }, `map`, `Maps the stream.`, P("stream"), P("f", V.Type(FunctionId)), )
var MaybeId = TypeIdentifier("Maybe")
var MaybeTypeObj = NewMaybeType()
var Maybe_Error = NewBuiltinFunction("Error", func(scope *Scope, args ...Object) Object { this := args[0].(*Maybe) if !this.Ok { return this.Error } return False })
var Maybe_Ok = NewBuiltinFunction("Ok", func(scope *Scope, args ...Object) Object { this := args[0].(*Maybe) return NewBoolean(this.Ok) })
---------------------------------------------------------------------------- Instance Methods ----------------------------------------------------------------------------
var Maybe_Result = NewBuiltinFunction("Result", func(scope *Scope, args ...Object) Object { this := args[0].(*Maybe) return this.Result() })
var Maybe_Value = NewBuiltinFunction("Value", func(scope *Scope, args ...Object) Object { this := args[0].(*Maybe) if this.Ok { return this.Value } return False })
var MinusOne = NewNumber(-1)
var ModuleId = TypeIdentifier("Module")
var Module_Math = NewModuleType("Math")
var Module_Math_Acos = makeMathFn(math.Acos, "Acos", "Acos returns the arccosine, in radians, of x.")
var Module_Math_Acosh = makeMathFn(math.Acosh, "Acosh", "Acosh returns the inverse hyperbolic cosine of x.")
var Module_Math_Asin = makeMathFn(math.Asin, "Asin", "Asin returns the arcsine, in radians, of x.")
var Module_Math_Asinh = makeMathFn(math.Asinh, "Asinh", "Asinh returns the inverse hyperbolic sine of x.")
var Module_Math_Atan = makeMathFn(math.Atan, "Atan", "Atan returns the arctangent, in radians, of x.")
var Module_Math_Atan2 = makeMathFn2Inv(math.Atan2, "Atan2", "Atan2 returns the arctangent of y/x, using the signs of the two to determine the quadrant of the result.")
var Module_Math_Atanh = makeMathFn(math.Atanh, "Atanh", "Atanh returns the inverse hyperbolic tangent of x.")
var Module_Math_Cbrt = makeMathFn(math.Cbrt, "Cbrt", "Cbrt returns the cube root of x.")
var Module_Math_Cos = makeMathFn(math.Cos, "Cos", "Cos returns the cosine of the radian argument x.")
var Module_Math_Cosh = makeMathFn(math.Cosh, "Cosh", "Cosh returns the hyperbolic cosine of x.")
var Module_Math_Deg = makeMathFn(func(x float64) float64 { return x * 180 / math.Pi }, "Deg", "Deg converts x from radians to degrees.")
var Module_Math_Dim = makeMathFn2(math.Dim, "Dim", "Dim returns the maximum of x-y or 0.")
var Module_Math_E = NewNumber(2.71828182845904523536028747135266249775724709369995957496696763) // https://oeis.org/A001113
var Module_Math_Erf = makeMathFn(math.Erf, "Erf", "Erf returns the error function of x.")
var Module_Math_Erfc = makeMathFn(math.Erfc, "Erfc", "Erfc returns the complementary error function of x.")
var Module_Math_Erfcinv = makeMathFn(math.Erfcinv, "Erfcinv", "Erfcinv returns the inverse of Erfc(x).")
var Module_Math_Erfinv = makeMathFn(math.Erfinv, "Erfinv", "Erfinv returns the inverse error function of x.")
var Module_Math_Exp = makeMathFn(math.Exp, "Exp", "Exp returns e**x, the base-e exponential of x.")
var Module_Math_Exp2 = makeMathFn(math.Exp2, "Exp2", "Exp2 returns 2**x, the base-2 exponential of x.")
var Module_Math_Expm1 = makeMathFn(math.Expm1, "Expm1", "Expm1 returns e**x - 1, the base-e exponential of x minus 1.")
var Module_Math_FMA = makeMathFn3(math.FMA, "FMA", "FMA returns x * y + z, computed with only one rounding.")
var Module_Math_Gamma = makeMathFn(math.Gamma, "Gamma", "Gamma returns the Gamma function of x.")
var Module_Math_Hypot = makeMathFn2(math.Hypot, "Hypot", "Hypot returns Sqrt(x*x + y*y), taking care to avoid overflow and underflow.")
var Module_Math_Ilogb = makeMathFn(func(x float64) float64 { return float64(math.Ilogb(x)) }, "Ilogb", "Ilogb returns the binary exponent of x.")
var Module_Math_J0 = makeMathFn(math.J0, "J0", "J0 returns the order-zero Bessel function of the first kind.")
var Module_Math_J1 = makeMathFn(math.J1, "J1", "J1 returns the order-one Bessel function of the first kind.")
var Module_Math_Jn = makeMathFn2(func(x float64, y float64) float64 { return math.Jn(int(x), y) }, "Jn", "Jn returns the order-n Bessel function of the first kind.")
var Module_Math_Ldexp = makeMathFn2(func(x float64, y float64) float64 { return math.Ldexp(x, int(y)) }, "Ldexp", "Ldexp is the inverse of Frexp. It sets x to mantissa * 2**exp and returns x.")
var Module_Math_Ln10 = NewNumber(2.30258509299404568401799145468436420760110148862877297603332790) // https://oeis.org/A002392
var Module_Math_Ln2 = NewNumber(0.693147180559945309417232121458176568075500134360255254120680009) // https://oeis.org/A002162
var Module_Math_Log = makeMathFn(math.Log, "Log", "Log returns the natural logarithm of x.")
var Module_Math_Log10 = makeMathFn(math.Log10, "Log10", "Log10 returns the decimal logarithm of x.")
var Module_Math_Log10E = NewNumber(1 / 2.30258509299404568401799145468436420760110148862877297603332790)
var Module_Math_Log1p = makeMathFn(math.Log1p, "Log1p", "Log1p returns the natural logarithm of 1 plus x.")
var Module_Math_Log2 = makeMathFn(math.Log2, "Log2", "Log2 returns the binary logarithm of x.")
var Module_Math_Log2E = NewNumber(1 / 0.693147180559945309417232121458176568075500134360255254120680009)
var Module_Math_Logb = makeMathFn(math.Logb, "Logb", "Logb returns the binary exponent of x.")
var Module_Math_Mod = makeMathFn2(math.Mod, "Mod", "Mod returns the floating-point remainder of x/y.")
var Module_Math_Nextafter = makeMathFn2(math.Nextafter, "Nextafter", "Nextafter returns the next representable float64 value after x in the direction of y.")
var Module_Math_Phi = NewNumber(1.61803398874989484820458683436563811772030917980576286213544862) // https://oeis.org/A001622
var Module_Math_Pi = NewNumber(3.14159265358979323846264338327950288419716939937510582097494459) // https://oeis.org/A000796
var Module_Math_Pow = makeMathFn2(math.Pow, "Pow", "Pow returns x**y, the base-x exponential of y.")
var Module_Math_Pow10 = makeMathFn(func(x float64) float64 { return math.Pow10(int(x)) }, "Pow10", "Pow10 returns 10**n, the base-10 exponential of n.")
var Module_Math_Primes = F( func(scope *Scope, args ...Object) Object { D := map[int]int{} q := 0 return NewInternalStream(func(s *Scope) Object { if q == 0 { q = 1 return YieldWith(Two) } for { q += 2 p, ok := D[q] if !ok { delete(D, q) D[q*q] = q return YieldWith(NewNumber(float64(q))) } else { x := q + 2*p for _, ok := D[x]; ok; { x += 2 * p _, ok = D[x] } D[x] = p } } }, scope) }, "Primes", "Generate infinite prime numbers.", )
var Module_Math_Rad = makeMathFn(func(x float64) float64 { return x * math.Pi / 180 }, "Rad", "Rad converts x from degrees to radians.")
var Module_Math_Sin = makeMathFn(math.Sin, "Sin", "Sin returns the sine of the radian argument x.")
var Module_Math_Sinh = makeMathFn(math.Sinh, "Sinh", "Sinh returns the hyperbolic sine of x.")
var Module_Math_Sqrt = makeMathFn(math.Sqrt, "Sqrt", "Sqrt returns the square root of x.")
var Module_Math_Sqrt2 = NewNumber(1.41421356237309504880168872420969807856967187537694807317667974) // https://oeis.org/A002193
var Module_Math_SqrtE = NewNumber(1.64872127070012814684865078781416357165377610071014801157507931) // https://oeis.org/A019774
var Module_Math_SqrtPhi = NewNumber(1.27201964951406896425242246173749149171560804184009624861664038) // https://oeis.org/A139339
var Module_Math_SqrtPi = NewNumber(1.77245385090551602729816748334114518279754945612238712821380779) // https://oeis.org/A002161
var Module_Math_Tan = makeMathFn(math.Tan, "Tan", "Tan returns the tangent of the radian argument x.")
var Module_Math_Tanh = makeMathFn(math.Tanh, "Tanh", "Tanh returns the hyperbolic tangent of x.")
var Module_Math_Y0 = makeMathFn(math.Y0, "Y0", "Y0 returns the order-zero Bessel function of the second kind.")
var Module_Math_Y1 = makeMathFn(math.Y1, "Y1", "Y1 returns the order-one Bessel function of the second kind.")
var Module_Math_Yn = makeMathFn2(func(x float64, y float64) float64 { return math.Yn(int(x), y) }, "Yn", "Yn returns the order-n Bessel function of the second kind.")
var NumberId = TypeIdentifier("Number")
var NumberTypeObj = NewNumberType()
var Number_Abs = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.Abs(this.Value)) }, `Abs`, `Returns the absolute value of a number.`, P("this", V.Type(NumberId)), )
var Number_Add = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(this.Value + other.Value) }, `Add`, `Returns the sum of two numbers.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Ceil = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.Ceil(this.Value)) }, `Ceil`, `Returns the smallest integer value greater than or equal to a number.`, P("this", V.Type(NumberId)), )
var Number_Clamp = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) min := args[1].(*Number) max := args[2].(*Number) return NewNumber(math.Min(math.Max(this.Value, min.Value), max.Value)) }, `Clamp`, `Clamps a number between a minimum and maximum value.`, P("this", V.Type(NumberId)), P("min", V.Type(NumberId)), P("max", V.Type(NumberId)), )
var Number_CopySign = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) sign := args[1].(*Number) return NewNumber(math.Copysign(this.Value, sign.Value)) }, `CopySign`, `Returns the value of the first number with the sign of the second number.`, P("this", V.Type(NumberId)), P("sign", V.Type(NumberId)), )
var Number_Div = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(this.Value / other.Value) }, `Div`, `Returns the division of two numbers.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Floor = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.Floor(this.Value)) }, `Floor`, `Returns the largest integer value less than or equal to a number.`, P("this", V.Type(NumberId)), )
var Number_Int = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.Trunc(this.Value)) }, `Int`, `Returns the integer value of a number.`, P("this", V.Type(NumberId)), )
var Number_IsEven = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewBoolean(int64(this.Value)%2 == 0) }, `IsEven`, `Returns true if the number is even.`, P("this", V.Type(NumberId)), )
var Number_IsOdd = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewBoolean(int64(this.Value)%2 != 0) }, `IsOdd`, `Returns true if the number is odd.`, P("this", V.Type(NumberId)), )
var Number_Max = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) for _, arg := range args[1:] { other := arg.(*Number) if other.Value > this.Value { this = other } } return this }, `Max`, `Returns the largest number from a list of numbers.`, P("this", V.Type(NumberId)), P("others", V.Type(NumberId)).AsSpread(), )
var Number_Min = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) for _, arg := range args[1:] { other := arg.(*Number) if other.Value < this.Value { this = other } } return this }, `Min`, `Returns the smallest number from a list of numbers.`, P("this", V.Type(NumberId)), P("others", V.Type(NumberId)).AsSpread(), )
var Number_Mod = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(math.Mod(this.Value, other.Value)) }, `Mod`, `Returns the remainder of a division between two numbers.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Mul = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(this.Value * other.Value) }, `Mul`, `Returns the product of two numbers.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Pow = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(math.Pow(this.Value, other.Value)) }, `Pow`, `Returns the first number raised to the power of the second number.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Remainder = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(math.Remainder(this.Value, other.Value)) }, `Remainder`, `Returns the remainder of a division between two numbers.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Round = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.Round(this.Value)) }, `Round`, `Returns the nearest integer value to a number.`, P("this", V.Type(NumberId)), )
var Number_RoundToEven = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.RoundToEven(this.Value)) }, `RoundToEven`, `Returns the nearest even integer value to a number.`, P("this", V.Type(NumberId)), )
var Number_Sign = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) if this.Value >= 0 { return One } return MinusOne }, `Sign`, `Returns the sign of a number, 1 for positive, -1 for negative.`, P("this", V.Type(NumberId)), )
var Number_Sub = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) other := args[1].(*Number) return NewNumber(this.Value - other.Value) }, `Sub`, `Returns the difference of two numbers.`, P("this", V.Type(NumberId)), P("other", V.Type(NumberId)), )
var Number_Truncate = F( func(scope *Scope, args ...Object) Object { this := args[0].(*Number) return NewNumber(math.Trunc(this.Value)) }, `Truncate`, `Returns the integer value of a number.`, P("this", V.Type(NumberId)), )
var One = NewNumber(1)
var Print = F( func(scope *Scope, args ...Object) Object { fmt.Print(_sprint(args...)) return NewTuple(args...) }, `print`, `Prints the values to the standard output.`, P("values").AsSpread(), )
var Printf = F( func(scope *Scope, args ...Object) Object { fmt.Print(_sprintf(args...)) return NewTuple(args...) }, `printf`, `Prints the formatted string to the standard output.`, P("format", V.Type(StringId)), P("values").AsSpread(), )
var Printfln = F( func(scope *Scope, args ...Object) Object { fmt.Print(_sprintf(args...)) fmt.Println() return NewTuple(args...) }, `printfln`, `Prints the formatted string to the standard output.`, P("format", V.Type(StringId)), P("values").AsSpread(), )
var Println = F( func(scope *Scope, args ...Object) Object { fmt.Println(_sprint(args...)) return NewTuple(args...) }, `println`, `Prints the values to the standard output.`, P("values").AsSpread(), )
var Range = F( func(scope *Scope, args ...Object) Object { start := 0. end := 0. step := 1. switch len(args) { case 1: end = args[0].(*Number).Value case 2: start = args[0].(*Number).Value end = args[1].(*Number).Value if start > end { step = -1 } case 3: start = args[0].(*Number).Value end = args[1].(*Number).Value step = args[2].(*Number).Value } cur := start inv := step < 0 return NewInternalStream(func(s *Scope) Object { if cur >= end && !inv || cur <= end && inv { return nil } r := cur cur += step return YieldWith(NewNumber(r)) }, scope) }, `range`, `Returns a range object.`, P("values", V.Type(NumberId)).AsSpread(), )
var Reduce = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) f := args[2].(*Function) acc := args[1] for { maybe := Stream_Next.Call(scope, stream) if isRaise(maybe) { return maybe } if stream.Finished { return acc } value := maybe.(*Maybe).Value acc = scope.Eval().Call(scope, f, toLambdaParams(acc, value)) if isRaise(acc) { return acc } } }, `reduce`, `Reduces the stream.`, P("stream"), P("acc"), P("f", V.Type(FunctionId)), )
var Sprint = F( func(scope *Scope, args ...Object) Object { return NewString(_sprint(args...)) }, `sprint`, `Returns the formatted string.`, P("values").AsSpread(), )
var Sprintf = F( func(scope *Scope, args ...Object) Object { return NewString(_sprintf(args...)) }, `sprintf`, `Returns the formatted string.`, P("format", V.Type(StringId)), P("values").AsSpread(), )
var Sprintfln = F( func(scope *Scope, args ...Object) Object { return NewString(_sprintf(args...) + "\n") }, `sprintfln`, `Returns the formatted string.`, P("format", V.Type(StringId)), P("values").AsSpread(), )
var Sprintln = F( func(scope *Scope, args ...Object) Object { return NewString(_sprint(args...)) }, `sprintln`, `Returns the formatted string.`, P("values").AsSpread(), )
var StreamId = TypeIdentifier("Stream")
var StreamIterationId = TypeIdentifier("stream_iteration")
var StreamTypeObj = NewStreamType()
var Stream_Finished = NewBuiltinFunction("Finished", func(scope *Scope, args ...Object) Object { this := args[0].(*Stream) return NewBoolean(this.Finished) })
var Stream_Next = NewBuiltinFunction("Next", func(scope *Scope, args ...Object) Object { this := args[0].(*Stream) if this.Finished { return NewMaybe(NewErrorFromString("Stream finished")) } var ret Object if this.Fn != nil { ret = scope.Eval().RawEval(this.Scope, this.Fn.Body) } else { ret = this.InternalFn(this.Scope) } if isRaise(ret) { return ret } if t := asYield(ret); t != nil { return NewMaybe(t.Value) } this.Finished = true return NewMaybe(NewErrorFromString("Stream finished")) })
---------------------------------------------------------------------------- Instance Methods ----------------------------------------------------------------------------
var StringId = TypeIdentifier("String")
var StringTypeObj = NewStringType()
var String_Chars = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) runes := []rune(this.Value) idx := 0 return NewInternalStream(func(s *Scope) Object { if idx >= len(runes) { return nil } r := runes[idx] idx++ return YieldWith(NewString(string(r))) }, scope) }, `Chars`, `Create a stream of characters from the string.`, P("this", V.Type(StringId)), )
---------------------------------------------------------------------------- Streams ----------------------------------------------------------------------------
var String_Contains = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) searches := args[1:] for _, e := range searches { search := e.(*String) if strings.Contains(this.Value, search.Value) { return True } } return False }, `Contains`, `Check if the string contains any of the given substrings.`, P("this", V.Type(StringId)), P("search", V.Type(StringId)).AsSpread(), )
---------------------------------------------------------------------------- Checkers ----------------------------------------------------------------------------
var String_ContainsChars = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) search := args[1].(*String) return NewBoolean(strings.ContainsAny(this.Value, search.Value)) }, `ContainsChars`, `Check if the string contains any of the characters in the given string.`, P("this", V.Type(StringId)), P("search", V.Type(StringId)), )
var String_Cut = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) index := int(args[1].(*Number).Value) len := str_len(this.Value) if index < 0 { index = len + index } if index < 0 { return NewTuple(EmptyString, this.Copy()) } else if index >= len { return NewTuple(this.Copy(), EmptyString) } runes := []rune(this.Value) return NewTuple( NewString(string(runes[:index])), NewString(string(runes[index:])), ) }, `Cut`, `Divide the string into two parts at the given index. Returns a tuple with the two parts.`, P("this", V.Type(StringId)), P("index", V.Type(NumberId)), )
var String_CutFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) f := args[1].(*Function) runes := []rune(this.Value) for idx, chr := range runes { ret := scope.Eval().Call(scope, f, []Object{ NewString(string(chr)), NewNumber(float64(idx)), }) if isRaise(ret) { return ret } if ret.AsBool() { return NewTuple( NewString(string(runes[:idx])), NewString(string(runes[idx:])), ) } } return NewTuple(this.Copy(), EmptyString) }, `CutFn`, `Divide the string into two parts when the provided function returns true. Returns a tuple with the two parts.`, P("this", V.Type(StringId)), P("f", V.Type(FunctionId)), )
var String_Ellipsis = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) max := int(args[1].(*Number).Value) if str_len(this.Value) <= max { return this.Copy() } runes := []rune(this.Value) return NewString(string(runes[:max]) + "...") }, `Ellipsis`, `Truncate the string to the given length and append an ellipsis.`, P("this", V.Type(StringId)), P("max", V.Type(NumberId)), )
---------------------------------------------------------------------------- Formats ----------------------------------------------------------------------------
var String_EndsWith = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) searches := args[1:] for _, e := range searches { search := e.(*String) if strings.HasSuffix(this.Value, search.Value) { return True } } return False }, `EndsWith`, `Check if the string ends with any of the given substrings.`, P("this", V.Type(StringId)), P("search", V.Type(StringId)).AsSpread(), )
var String_Fields = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) parts := strings.Fields(this.Value) objs := make([]Object, len(parts)) for i, part := range parts { objs[i] = NewString(part) } return NewList(objs...) }, `Fields`, `Split the string into a list of substrings, using white spaces as separators.`, P("this", V.Type(StringId)), )
var String_Find = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) runes := []rune(this.Value) idx := 0 for i, chr := range runes { if strings.HasPrefix(this.Value[idx:], sub.Value) { return NewNumber(float64(i)) } idx += utf8.RuneLen(chr) } return NewNumber(float64(-1)) }, `Find`, `Find the first occurrence of the substring in the string. Returns the index of the first character of the substring, or -1 if not found.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_FindAny = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) runes := []rune(this.Value) idx := 0 for i, chr := range runes { if strings.ContainsRune(sub.Value, chr) { return NewNumber(float64(i)) } idx += utf8.RuneLen(chr) } return NewNumber(float64(-1)) }, `FindAny`, `Find the first occurrence of any of the characters in the string. Returns the index of the first character, or -1 if not found.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_FindFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) f := args[1].(*Function) runes := []rune(this.Value) for idx, chr := range runes { ret := scope.Eval().Call(scope, f, []Object{ NewString(string(chr)), NewNumber(float64(idx)), }) if isRaise(ret) { return ret } if ret.AsBool() { return NewNumber(float64(idx)) } } return NewNumber(-1) }, `FindFn`, `Find the first occurrence of a character in the string that satisfies the function. Returns the index of the character, or -1 if not found.`, P("this", V.Type(StringId)), P("f", V.Type(FunctionId)), )
var String_FindLast = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) runes := []rune(this.Value) idx := len(this.Value) for i := len(runes) - 1; i >= 0; i-- { chr := runes[i] idx -= utf8.RuneLen(chr) if strings.HasPrefix(this.Value[idx:], sub.Value) { return NewNumber(float64(i)) } } return NewNumber(float64(-1)) }, `FindLast`, `Find the last occurrence of the substring in the string. Returns the index of the first character of the substring, or -1 if not found.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_FindLastAny = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) runes := []rune(this.Value) for i := len(runes) - 1; i >= 0; i-- { chr := runes[i] if strings.ContainsRune(sub.Value, chr) { return NewNumber(float64(i)) } } return NewNumber(float64(-1)) }, `FindLastAny`, `Find the last occurrence of any of the characters in the string. Returns the index of the first character, or -1 if not found.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_FindLastFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) f := args[1].(*Function) runes := []rune(this.Value) for idx := len(runes) - 1; idx >= 0; idx-- { chr := runes[idx] ret := scope.Eval().Call(scope, f, []Object{ NewString(string(chr)), NewNumber(float64(idx)), }) if isRaise(ret) { return ret } if ret.AsBool() { return NewNumber(float64(idx)) } } return NewNumber(-1) }, `FindLastFn`, `Find the last occurrence of a character in the string that satisfies the function. Returns the index of the character, or -1 if not found.`, P("this", V.Type(StringId)), P("f", V.Type(FunctionId)), )
var String_Get = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) index := int(args[1].(*Number).Value) len := str_len(this.Value) if index < 0 { index = len + index } if index < 0 || index >= len { return scope.Interrupt(Raise("string index '%d' out of bounds", index)) } runes := []rune(this.Value) return NewString(string(runes[index])) }, `Get`, `Returns the character at the given index. Raise an error if the index is out of bounds.`, P("this", V.Type(StringId)), P("index", V.Type(NumberId)), )
var String_GetOr = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) index := int(args[1].(*Number).Value) len := str_len(this.Value) if index < 0 { index = len + index } if index < 0 || index >= len { return args[2] } runes := []rune(this.Value) return NewString(string(runes[index])) }, `GetOr`, `Returns the character at the given index. Returns the default value if the index is out of bounds.`, P("this", V.Type(StringId)), P("index", V.Type(NumberId)), P("default", V.Type(StringId)), )
var String_IsEmpty = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewBoolean(this.Value == "") }, `IsEmpty`, `Check if the string is empty.`, P("this", V.Type(StringId)), )
var String_Join = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) list := args[1].(*List) elements := make([]string, len(list.Elements)) for i, e := range list.Elements { elements[i] = e.AsString() } return NewString(string(strings.Join(elements, this.Value))) }, `Join`, `Join the elements of a list into a new string, using the current string as the separator.`, P("this", V.Type(StringId)), P("list", V.Type(ListId)), )
---------------------------------------------------------------------------- Conversions ----------------------------------------------------------------------------
var String_JoinArgs = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) elements := make([]string, len(args)-1) for i, e := range args[1:] { elements[i] = e.AsString() } return NewString(string(strings.Join(elements, this.Value))) }, `JoinArgs`, `Join the elements of a list into a new string, using the current string as the separator.`, P("this", V.Type(StringId)), P("args").AsSpread(), )
var String_Lines = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) runes := []rune(this.Value) pivot := 0 idx := 0 return NewInternalStream(func(s *Scope) Object { for { if idx >= len(runes) { if pivot < idx { line := runes[pivot:] pivot = idx + 1 return YieldWith(NewString(string(line))) } else if pivot == idx { pivot = idx + 1 return YieldWith(EmptyString) } return nil } chr := runes[idx] idx++ if chr == '\n' { line := runes[pivot : idx-1] pivot = idx return YieldWith(NewString(string(line))) } } }, scope) }, `Lines`, `Create a stream of lines from the string.`, P("this", V.Type(StringId)), )
var String_PadCenter = F( func(scope *Scope, args ...Object) Object { return String_PadCenterWith.Call(scope, args[0], args[1], NewString(" ")) }, `PadCenter`, `Pad the string with spaces to the given size, centering the content.`, P("this", V.Type(StringId)), P("size", V.Type(NumberId)), )
var String_PadCenterWith = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) size := int(args[1].(*Number).Value) pad := args[2].(*String).Value len := str_len(this.Value) if len >= size { return this.Copy() } left := (size - len) / 2 right := size - len - left return NewString(strings.Repeat(pad, left) + this.Value + strings.Repeat(pad, right)) }, `PadCenterWith`, `Pad the string with the provided pad string to the given size, centering the content.`, P("this", V.Type(StringId)), P("size", V.Type(NumberId)), P("pad", V.Type(StringId)), )
var String_PadLeft = F( func(scope *Scope, args ...Object) Object { return String_PadLeftWith.Call(scope, args[0], args[1], NewString(" ")) }, `PadLeft`, `Pad the string with spaces to the given size, aligning the content to the right.`, P("this", V.Type(StringId)), P("size", V.Type(NumberId)), )
var String_PadLeftWith = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) size := int(args[1].(*Number).Value) pad := args[2].(*String).Value len := str_len(this.Value) if len >= size { return this.Copy() } return NewString(strings.Repeat(pad, size-len) + this.Value) }, `PadLeftWith`, `Pad the string with the provided pad string to the given size, aligning the content to the right.`, P("this", V.Type(StringId)), P("size", V.Type(NumberId)), P("pad", V.Type(StringId)), )
var String_PadRight = F( func(scope *Scope, args ...Object) Object { return String_PadRightWith.Call(scope, args[0], args[1], NewString(" ")) }, `PadRight`, `Pad the string with spaces to the given size, aligning the content to the left.`, P("this", V.Type(StringId)), P("size", V.Type(NumberId)), )
var String_PadRightWith = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) size := int(args[1].(*Number).Value) pad := args[2].(*String).Value len := str_len(this.Value) if len >= size { return this.Copy() } return NewString(this.Value + strings.Repeat(pad, size-len)) }, `PadRightWith`, `Pad the string with the provided pad string to the given size, aligning the content to the left.`, P("this", V.Type(StringId)), P("size", V.Type(NumberId)), P("pad", V.Type(StringId)), )
var String_Repeat = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) times := int(args[1].(*Number).Value) return NewString(strings.Repeat(this.Value, times)) }, `Repeat`, `Repeat the string the given number of times.`, P("this", V.Type(StringId)), P("times", V.Type(NumberId)), )
var String_Replace = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) old := args[1].(*String) new := args[2].(*String) return NewString(strings.ReplaceAll(this.Value, old.Value, new.Value)) }, `Replace`, `Replace all occurrences of the old substring with the new one.`, P("this", V.Type(StringId)), P("old", V.Type(StringId)), P("new", V.Type(StringId)), )
var String_ReplaceN = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) old := args[1].(*String) new := args[2].(*String) n := int(args[3].(*Number).Value) return NewString(strings.Replace(this.Value, old.Value, new.Value, n)) }, `ReplaceN`, `Replace the first n occurrences of the old substring with the new one.`, P("this", V.Type(StringId)), P("old", V.Type(StringId)), P("new", V.Type(StringId)), P("n", V.Type(NumberId)), )
var String_Reverse = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) runes := []rune(this.Value) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return NewString(string(runes)) }, `Reverse`, `Reverse the string.`, P("this", V.Type(StringId)), )
var String_Size = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewNumber(float64(str_len(this.Value))) }, `Size`, `Returns the number of characters in the string.`, P("this", V.Type(StringId)), )
---------------------------------------------------------------------------- Accessors ----------------------------------------------------------------------------
var String_Sort = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) runes := []rune(this.Value) slices.Sort(runes) return NewString(string(runes)) }, `Sort`, `Sort the characters of the string.`, P("this", V.Type(StringId)), )
var String_SortFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) fn := args[1].(*Function) runes := []rune(this.Value) slices.SortFunc(runes, func(a, b rune) int { ret := scope.Eval().Call(scope, fn, []Object{ NewString(string(a)), NewString(string(b)), }) if isRaise(ret) { return 0 } n, ok := ret.(*Number) if !ok { return 0 } return int(n.Value) }) return NewString(string(runes)) }, `SortFn`, `Sort the characters of the string given the function.`, P("this", V.Type(StringId)), P("f", V.Type(FunctionId)), )
var String_Split = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) items := strings.Split(this.Value, sub.Value) objs := make([]Object, len(items)) for i, item := range items { objs[i] = NewString(item) } return NewList(objs...) }, `Split`, `Split the string into a list of substrings, given the separator.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_SplitAt = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) index := int(args[1].(*Number).Value) len := str_len(this.Value) runes := []rune(this.Value) if index < 0 { index = len + index } if index < 0 { return NewList(EmptyString, this.Copy()) } else if index >= len { return NewList(this.Copy(), EmptyString) } return NewList( NewString(string(runes[:index])), NewString(string(runes[index:])), ) }, `SplitAt`, `Split the string into a list of substrings, given the index.`, P("this", V.Type(StringId)), P("index", V.Type(NumberId)), )
var String_SplitFn = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) f := args[1].(*Function) parts := []Object{} lastIdx := 0 runes := []rune(this.Value) for idx, chr := range runes { ret := scope.Eval().Call(scope, f, []Object{ NewString(string(chr)), NewNumber(float64(idx)), }) if isRaise(ret) { return ret } if ret.AsBool() { parts = append(parts, NewString(string(runes[lastIdx:idx]))) lastIdx = idx } } if lastIdx < len(this.Value) { parts = append(parts, NewString(string(runes[lastIdx:]))) } return NewList(parts...) }, `SplitFn`, `Split the string into a list of substrings, given the function.`, P("this", V.Type(StringId)), P("f", V.Type(FunctionId)), )
var String_StartsWith = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) searches := args[1:] for _, e := range searches { search := e.(*String) if strings.HasPrefix(this.Value, search.Value) { return True } } return False }, `StartsWith`, `Check if the string starts with any of the given substrings.`, P("this", V.Type(StringId)), P("search", V.Type(StringId)).AsSpread(), )
var String_Sub = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) from := int(args[1].(*Number).Value) to := int(args[2].(*Number).Value) len := str_len(this.Value) if from < 0 { from = len + from } if to < 0 { to = len + to } if to < from || to < 0 || from >= len { return EmptyString } from = max(0, from) to = min(len, to) runes := []rune(this.Value) return NewString(string(runes[from:to])) }, `Sub`, `Returns a substring starting from the given index up to the end index. Returns empty if the range is completely out of bounds. You may use negative indexes to start from the end of the string. `, P("this", V.Type(StringId)), P("from", V.Type(NumberId)), P("to", V.Type(NumberId)), )
var String_ToCamel = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) s := snakeReplacer.ReplaceAllString(this.Value, " ") words := strings.Fields(s) if len(words) == 0 { return EmptyString } words[0] = toLower.String(words[0]) for i, word := range words[1:] { words[i+1] = toTitle.String(word) } return NewString(strings.Join(words, "")) }, `ToCamel`, `Converts the string to camel case.`, P("this", V.Type(StringId)), )
var String_ToDot = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) s := snakeReplacer.ReplaceAllString(this.Value, " ") words := strings.Fields(s) return NewString(strings.ToLower(strings.Join(words, "."))) }, `ToDot`, `Converts the string to dot case.`, P("this", V.Type(StringId)), )
var String_ToKebab = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) s := snakeReplacer.ReplaceAllString(this.Value, " ") words := strings.Fields(s) return NewString(strings.ToLower(strings.Join(words, "-"))) }, `ToKebab`, `Converts the string to kebab case.`, P("this", V.Type(StringId)), )
var String_ToLower = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewString(toLower.String(this.Value)) }, `ToLower`, `Converts the string to lower case.`, P("this", V.Type(StringId)), )
var String_ToPascal = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) s := snakeReplacer.ReplaceAllString(this.Value, " ") words := strings.Fields(s) for i, word := range words { words[i] = toTitle.String(word) } return NewString(strings.Join(words, "")) }, `ToPascal`, `Converts the string to pascal case.`, P("this", V.Type(StringId)), )
var String_ToSentence = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) if len(this.Value) == 0 { return EmptyString } firstRune, size := utf8.DecodeRuneInString(this.Value) word := string(toUpper.String(string(firstRune))) + this.Value[size:] return NewString(word) }, `ToSentence`, `Converts the string to sentence case.`, P("this", V.Type(StringId)), )
var String_ToSnake = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) s := snakeReplacer.ReplaceAllString(this.Value, " ") words := strings.Fields(s) return NewString(strings.ToLower(strings.Join(words, "_"))) }, `ToSnake`, `Converts the string to snake case.`, P("this", V.Type(StringId)), )
var String_ToTitle = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewString(toTitle.String(this.Value)) }, `ToTitle`, `Converts the string to title case.`, P("this", V.Type(StringId)), )
var String_ToTrain = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) s := snakeReplacer.ReplaceAllString(this.Value, " ") words := strings.Fields(s) for i, word := range words { words[i] = toTitle.String(word) } return NewString(strings.Join(words, "-")) }, `ToTrain`, `Converts the string to train case.`, P("this", V.Type(StringId)), )
var String_ToUpper = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewString(toUpper.String(this.Value)) }, `ToUpper`, `Converts the string to upper case.`, P("this", V.Type(StringId)), )
var String_Trim = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) return NewString(strings.Trim(this.Value, sub.Value)) }, `Trim`, `Remove the given characters from the beginning and end of the string.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_TrimLeft = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) return NewString(strings.TrimLeft(this.Value, sub.Value)) }, `TrimLeft`, `Remove the given characters from the beginning of the string.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_TrimRight = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) sub := args[1].(*String) return NewString(strings.TrimRight(this.Value, sub.Value)) }, `TrimRight`, `Remove the given characters from the end of the string.`, P("this", V.Type(StringId)), P("sub", V.Type(StringId)), )
var String_TrimSpace = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewString(strings.TrimSpace(this.Value)) }, `TrimSpace`, `Remove leading and trailing white spaces from the string.`, P("this", V.Type(StringId)), )
var String_TrimSpaceLeft = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewString(strings.TrimLeft(this.Value, " \t\n\r")) }, `TrimSpaceLeft`, `Remove leading white spaces from the string.`, P("this", V.Type(StringId)), )
var String_TrimSpaceRight = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) return NewString(strings.TrimRight(this.Value, " \t\n\r")) }, `TrimSpaceRight`, `Remove trailing white spaces from the string.`, P("this", V.Type(StringId)), )
var String_Words = F( func(scope *Scope, args ...Object) Object { this := args[0].(*String) runes := []rune(this.Value) pivot := 0 idx := 0 return NewInternalStream(func(s *Scope) Object { for { if idx >= len(runes) { if pivot < idx { word := runes[pivot:] pivot = idx + 1 return YieldWith(NewString(string(word))) } return nil } chr := runes[idx] idx++ if chr == ' ' || chr == '\t' || chr == '\n' || chr == '\r' { if pivot < idx-1 { word := runes[pivot : idx-1] pivot = idx println(string(word)) return YieldWith(NewString(string(word))) } pivot = idx } } }, scope) }, `Words`, `Create a stream of words from the string.`, P("this", V.Type(StringId)), )
var Sum = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) sum := 0. for { maybe := Stream_Next.Call(scope, stream) if isRaise(maybe) { return maybe } if stream.Finished { return NewNumber(sum) } value := maybe.(*Maybe).Value if v, ok := value.(*Tuple); ok { value = v.Elements[0] } number, ok := value.(*Number) if !ok { return scope.Interrupt(Raise("expected number, got %s", value.Type())) } sum += number.Value } }, `sum`, `Sums the stream.`, P("stream"), )
var SumBy = F( func(scope *Scope, args ...Object) Object { s := StreamTypeObj.Convert(scope, args[0]) if isRaise(s) { return s } stream := s.(*Stream) f := args[1].(*Function) sum := 0. for { maybe := Stream_Next.Call(scope, stream) if isRaise(maybe) { return maybe } if stream.Finished { return NewNumber(sum) } value := maybe.(*Maybe).Value ret := scope.Eval().Call(scope, f, toLambdaParams(value)) if isRaise(ret) { return ret } number, ok := ret.(*Number) if !ok { return scope.Interrupt(Raise("expected number, got %s", value.Type())) } sum += number.Value } }, `sumBy`, `Sums the stream.`, P("stream"), P("f", V.Type(FunctionId)), )
var True = internalBoolean(true)
var TupleId = TypeIdentifier("Tuple")
var TupleTypeObj = NewTupleType()
var Two = NewNumber(2)
var TypeId = TypeIdentifier("Type")
var TypeTypeObj = NewType()
var V = &Validator{}
var Zero = NewNumber(0)
Functions ¶
This section is empty.
Types ¶
type ActiveRecord ¶
type ActiveRecord interface { }
Active records are used to store the current state of the evaluation in case of interruptions. Particularly used for yield interruptions, so the evaluator can resume the evaluation from the last active record.
type BaseObject ¶
type BaseObject struct {
// contains filtered or unexported fields
}
---------------------------------------------------------------------------- BaseObject Definition ----------------------------------------------------------------------------
func NewBaseObject ¶
func NewBaseObject(otype ObjectType) *BaseObject
func (*BaseObject) AddMethod ¶
func (o *BaseObject) AddMethod(fn *BuiltinFunction)
func (*BaseObject) AsBool ¶
func (o *BaseObject) AsBool() bool
func (*BaseObject) AsInterface ¶
func (o *BaseObject) AsInterface() any
func (*BaseObject) AsRepr ¶
func (o *BaseObject) AsRepr() string
func (*BaseObject) AsString ¶
func (o *BaseObject) AsString() string
func (*BaseObject) Docs ¶
func (o *BaseObject) Docs() string
func (*BaseObject) GetProperty ¶
func (o *BaseObject) GetProperty(name string) Object
func (*BaseObject) Id ¶
func (o *BaseObject) Id() string
func (*BaseObject) OnIndexAssign ¶
func (o *BaseObject) OnIndexAssign(scope *Scope, t *Tuple, value Object) Object
func (*BaseObject) OnOperator ¶
func (o *BaseObject) OnOperator(scope *Scope, op string, right Object) Object
func (*BaseObject) Parent ¶
func (o *BaseObject) Parent() Object
func (*BaseObject) SetDocs ¶
func (o *BaseObject) SetDocs(docs string)
func (*BaseObject) SetParent ¶
func (o *BaseObject) SetParent(p Object)
func (*BaseObject) SetProperty ¶
func (o *BaseObject) SetProperty(name string, value Object)
func (*BaseObject) Type ¶
func (o *BaseObject) Type() ObjectType
func (*BaseObject) TypeId ¶
func (o *BaseObject) TypeId() TypeIdentifier
type BaseObjectType ¶
type BaseObjectType struct { *BaseObject // contains filtered or unexported fields }
---------------------------------------------------------------------------- BaseObjectType Definition ----------------------------------------------------------------------------
func NewBaseObjectType ¶
func NewBaseObjectType(baseObject *BaseObject, typeId TypeIdentifier) *BaseObjectType
func (*BaseObjectType) AsBool ¶
func (o *BaseObjectType) AsBool() bool
func (*BaseObjectType) AsRepr ¶
func (o *BaseObjectType) AsRepr() string
func (*BaseObjectType) AsString ¶
func (o *BaseObjectType) AsString() string
func (*BaseObjectType) TypeId ¶
func (o *BaseObjectType) TypeId() TypeIdentifier
type Boolean ¶
type Boolean struct { *BaseObject Value bool }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*Boolean) AsInterface ¶
type BooleanType ¶
type BooleanType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Boolean`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewBooleanType ¶
func NewBooleanType() *BooleanType
func (*BooleanType) Instantiate ¶
func (o *BooleanType) Instantiate(scope *Scope) Object
type BuiltinFn ¶
---------------------------------------------------------------------------- Builtin Functions ----------------------------------------------------------------------------
type BuiltinFunction ¶
type BuiltinFunction struct { *BaseObject Name string Fn BuiltinFn Signature []*Param }
func F ¶
func F(fn BuiltinFn, name, docs string, params ...*Param) *BuiltinFunction
Shortcut for builtin functions with parameters
func NewBuiltinFunction ¶
func NewBuiltinFunction(name string, fn BuiltinFn) *BuiltinFunction
func (*BuiltinFunction) AsBool ¶
func (o *BuiltinFunction) AsBool() bool
func (*BuiltinFunction) AsInterface ¶
func (o *BuiltinFunction) AsInterface() any
func (*BuiltinFunction) AsRepr ¶
func (o *BuiltinFunction) AsRepr() string
func (*BuiltinFunction) AsString ¶
func (o *BuiltinFunction) AsString() string
func (*BuiltinFunction) Check ¶
func (o *BuiltinFunction) Check(scope *Scope, args ...Object) Object
func (*BuiltinFunction) WithDocs ¶
func (o *BuiltinFunction) WithDocs(d string) *BuiltinFunction
func (*BuiltinFunction) WithSignature ¶
func (o *BuiltinFunction) WithSignature(params ...*Param) *BuiltinFunction
type Data ¶
type Data struct {
*BaseObject
}
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
type DataType ¶
type DataType struct { *BaseObjectType Name string Attributes map[string]ast.Node Methods map[string]*Function }
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Data`, `String` or even `Type`. ---------------------------------------------------------------------------- The data type should be created by user
func NewDataType ¶
func (*DataType) Instantiate ¶
type Dict ¶
type Dict struct { *BaseObject Elements map[string]Object }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*Dict) AsInterface ¶
type DictType ¶
type DictType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewDictType ¶
func NewDictType() *DictType
func (*DictType) Instantiate ¶
type Error ¶
type Error struct { *BaseObject Message string }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func NewErrorFromString ¶
func (*Error) AsInterface ¶
type ErrorType ¶
type ErrorType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewErrorType ¶
func NewErrorType() *ErrorType
func (*ErrorType) Instantiate ¶
type Function ¶
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func NewFunction ¶
type FunctionType ¶
type FunctionType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Function`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewFunctionType ¶
func NewFunctionType() *FunctionType
func (*FunctionType) Instantiate ¶
func (o *FunctionType) Instantiate(scope *Scope) Object
type Interruption ¶
type Interruption struct { *BaseObject Category InterruptionType TriggeredScope *Scope Value Object Context any Stack []ast.Node }
func Raise ¶
func Raise(msg string, v ...any) *Interruption
func RaiseWith ¶
func RaiseWith(value Object) *Interruption
func Return ¶
func Return(msg string, v ...any) *Interruption
func ReturnWith ¶
func ReturnWith(value Object) *Interruption
func Yield ¶
func Yield(msg string, v ...any) *Interruption
func YieldWith ¶
func YieldWith(value Object) *Interruption
func (*Interruption) AsBool ¶
func (i *Interruption) AsBool() bool
func (*Interruption) AsString ¶
func (i *Interruption) AsString() string
func (*Interruption) Docs ¶
func (i *Interruption) Docs() string
func (*Interruption) GetProperty ¶
func (i *Interruption) GetProperty(string) Object
func (*Interruption) Id ¶
func (i *Interruption) Id() string
func (*Interruption) SetDocs ¶
func (i *Interruption) SetDocs(string)
func (*Interruption) SetProperty ¶
func (i *Interruption) SetProperty(string, Object)
func (*Interruption) Type ¶
func (i *Interruption) Type() ObjectType
func (*Interruption) TypeId ¶
func (i *Interruption) TypeId() TypeIdentifier
type InterruptionType ¶
type InterruptionType string
var ( ReturnId InterruptionType = "return" RaiseId InterruptionType = "raise" YieldId InterruptionType = "yield" BreakId InterruptionType = "break" ContinueId InterruptionType = "continue" DeferredFunctionId InterruptionType = "deferred_function" )
type List ¶
type List struct { *BaseObject Elements []Object }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*List) AsInterface ¶
type ListType ¶
type ListType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewListType ¶
func NewListType() *ListType
func (*ListType) Instantiate ¶
type Maybe ¶
type Maybe struct { *BaseObject Ok bool Value Object Error Object ValueType TypeIdentifier }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func NewMaybeWithType ¶
func NewMaybeWithType(obj Object, tp TypeIdentifier) *Maybe
func (*Maybe) AsInterface ¶
type MaybeType ¶
type MaybeType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewMaybeType ¶
func NewMaybeType() *MaybeType
func (*MaybeType) Instantiate ¶
type ModuleType ¶
type ModuleType struct { *BaseObjectType Name string }
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Data`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewModuleType ¶
func NewModuleType(name string) *ModuleType
func (*ModuleType) AsString ¶
func (o *ModuleType) AsString() string
func (*ModuleType) Instantiate ¶
func (o *ModuleType) Instantiate(scope *Scope) Object
type Number ¶
type Number struct { *BaseObject Value float64 }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*Number) AsInterface ¶
type NumberType ¶
type NumberType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewNumberType ¶
func NewNumberType() *NumberType
func (*NumberType) Instantiate ¶
func (o *NumberType) Instantiate(scope *Scope) Object
type Object ¶
type Object interface { Id() string // Unique identifier for the instance TypeId() TypeIdentifier // Type ID, used to identify which struct we should use Type() ObjectType Docs() string SetDocs(string) Parent() Object SetParent(Object) GetProperty(string) Object SetProperty(string, Object) OnIndex(*Scope, *Tuple) Object OnIndexAssign(*Scope, *Tuple, Object) Object OnOperator(*Scope, string, Object) Object AsBool() bool AsString() string AsRepr() string AsInterface() any }
Represent any instance in Pipe
func GetBoolean ¶
func GetInverseBoolean ¶
func NewBoolean ¶
type ObjectType ¶
type ObjectType interface { Object AddMethod(*BuiltinFunction) Convert(*Scope, Object) Object Instantiate(*Scope) Object }
Represent type instances, like `Number`, `String` or even `Type`
type Param ¶
type Param struct { Name string Spread bool Validations []ValidationFn }
func P ¶
func P(name string, validations ...ValidationFn) *Param
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
func (*Scope) ActiveRecord ¶
func (s *Scope) ActiveRecord() ActiveRecord
func (*Scope) Interrupt ¶
func (s *Scope) Interrupt(interruption *Interruption) Object
TODO: add stack trace and active record?
func (*Scope) SetActiveRecord ¶
func (s *Scope) SetActiveRecord(ar ActiveRecord)
type Stream ¶
type Stream struct { *BaseObject Finished bool Scope *Scope Fn *Function InternalFn func(*Scope) Object // contains filtered or unexported fields }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*Stream) AsInterface ¶
type StreamIteration ¶
type StreamIteration struct { *BaseObject Stream *Stream }
func (*StreamIteration) AsBool ¶
func (i *StreamIteration) AsBool() bool
func (*StreamIteration) AsString ¶
func (i *StreamIteration) AsString() string
func (*StreamIteration) Docs ¶
func (i *StreamIteration) Docs() string
func (*StreamIteration) GetProperty ¶
func (i *StreamIteration) GetProperty(string) Object
func (*StreamIteration) Id ¶
func (i *StreamIteration) Id() string
func (*StreamIteration) SetDocs ¶
func (i *StreamIteration) SetDocs(string)
func (*StreamIteration) SetProperty ¶
func (i *StreamIteration) SetProperty(string, Object)
func (*StreamIteration) Type ¶
func (i *StreamIteration) Type() ObjectType
func (*StreamIteration) TypeId ¶
func (i *StreamIteration) TypeId() TypeIdentifier
type StreamType ¶
type StreamType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewStreamType ¶
func NewStreamType() *StreamType
func (*StreamType) Instantiate ¶
func (o *StreamType) Instantiate(scope *Scope) Object
type String ¶
type String struct { *BaseObject Value string }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*String) AsInterface ¶
type StringType ¶
type StringType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `String`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewStringType ¶
func NewStringType() *StringType
func (*StringType) Instantiate ¶
func (o *StringType) Instantiate(scope *Scope) Object
type Tuple ¶
type Tuple struct { *BaseObject Elements []Object }
---------------------------------------------------------------------------- Instance Definition - represents the instance of a particular type in Pipe, like `1` and `'foo'`. ----------------------------------------------------------------------------
func (*Tuple) AsInterface ¶
type TupleType ¶
type TupleType struct {
*BaseObjectType
}
---------------------------------------------------------------------------- Type Definition - represents the type instance in Pipe, like `Number`, `String` or even `Type`. ----------------------------------------------------------------------------
func NewTupleType ¶
func NewTupleType() *TupleType
func (*TupleType) Instantiate ¶
type Type ¶
type Type struct {
*BaseObject
}
func (*Type) Instantiate ¶
func (*Type) TypeId ¶
func (o *Type) TypeId() TypeIdentifier
type ValidationFn ¶
type Validator ¶
type Validator struct{}
func (*Validator) Type ¶
func (v *Validator) Type(typeId TypeIdentifier) ValidationFn
Source Files ¶
- active-record.go
- boolean.go
- builtin-functions.go
- data.go
- dict-methods.go
- dict.go
- error.go
- function.go
- interruption.go
- list-methods.go
- list.go
- maybe.go
- module-math.go
- module.go
- number-methods.go
- number.go
- object.go
- scope.go
- stream-iteration.go
- stream.go
- string-methods.go
- string.go
- tuple.go
- type.go
- utilities.go