Explicit self (#3569)

This change modifies the current language by requiring explicit `self` parameter declaration
for methods. Methods without `self` parameter in the first position should be treated as statics
although that is not yet part of this PR. We add an implicit self to all methods
This obviously required updating the whole stdlib and its components, tests etc but the change
is pretty straightforward in the diff.

Notice that this change **does not** change method dispatch, which was removed in the last changes.
This was done on purpose to simplify the implementation for now. We will likely still remove all
those implicit selfs to bring true statics.
Minor caveat - since `main` doesn't actually need self, already removed that which simplified
a lot of code.
This commit is contained in:
Hubert Plociniczak 2022-07-27 19:45:36 +02:00 committed by GitHub
parent a54a7d5553
commit f63e40df1b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
244 changed files with 2386 additions and 1694 deletions

View File

@ -295,6 +295,7 @@
- [Replace `this` with `self`][3524]
- [Introduce a smaller version of the standard library, just for testing][3531]
- [Remove `here` and make method name resolution case-sensitive][3531]
- [Explicit `self`][3569]
- [Added benchmarking tool for the language server][3578]
[3227]: https://github.com/enso-org/enso/pull/3227
@ -329,6 +330,7 @@
[3531]: https://github.com/enso-org/enso/pull/3531
[3562]: https://github.com/enso-org/enso/pull/3562
[3538]: https://github.com/enso-org/enso/pull/3538
[3538]: https://github.com/enso-org/enso/pull/3569
[3578]: https://github.com/enso-org/enso/pull/3578
# Enso 2.0.0-alpha.18 (2021-10-12)

View File

@ -30,7 +30,7 @@ type Any
7.to_text
to_text : Text
to_text = @Builtin_Method "Any.to_text"
to_text self = @Builtin_Method "Any.to_text"
## Generic conversion of an arbitrary Enso value to a corresponding human-readable
representation.
@ -40,7 +40,7 @@ type Any
7.to_text
to_display_text : Text
to_display_text = @Builtin_Method "Any.to_display_text"
to_display_text self = @Builtin_Method "Any.to_display_text"
## ALIAS Equality
@ -75,7 +75,7 @@ type Any
a = 7 * 21
a == 147
== : Any -> Boolean
== that = if Meta.is_same_object self that then True else
== self that = if Meta.is_same_object self that then True else
self_meta = Meta.meta self
that_meta = Meta.meta that
case Cons self_meta that_meta of
@ -118,7 +118,7 @@ type Any
a = 7 * 21
a != 147
!= : Any -> Boolean
!= that = (self == that).not
!= self that = (self == that).not
## ALIAS Greater Than
@ -143,7 +143,7 @@ type Any
a = 7 * 28
a > 147
> : Any -> Boolean
> that = self.compare_to that == Ordering.Greater
> self that = self.compare_to that == Ordering.Greater
## ALIAS Greater Than or Equal
@ -169,7 +169,7 @@ type Any
a = 6 * 21
a >= 147
>= : Any -> Boolean
>= that =
>= self that =
ordering = self.compare_to that
(ordering == Ordering.Greater) || (ordering == Ordering.Equal)
@ -196,7 +196,7 @@ type Any
a = 7 * 21
a < 147
< : Any -> Boolean
< that = self.compare_to that == Ordering.Less
< self that = self.compare_to that == Ordering.Less
## ALIAS Less Than or Equal
@ -222,7 +222,7 @@ type Any
a = 7 * 21
a < 147
<= : Any -> Boolean
<= that =
<= self that =
ordering = self.compare_to that
(ordering == Ordering.Less) || (ordering == Ordering.Equal)
@ -236,7 +236,7 @@ type Any
1.is_nothing
is_nothing : Boolean
is_nothing = False
is_nothing self = False
## UNSTABLE
If `self` is Nothing then returns `function`.
@ -246,7 +246,7 @@ type Any
"Hello".if_nothing ""
if_nothing : Any -> Any
if_nothing ~_ = self
if_nothing self ~_ = self
## Executes the provided handler on an error, or returns the value unchanged.
@ -274,7 +274,7 @@ type Any
error = Error.throw 42
error.catch == 42
catch : Any -> (Error -> Any) -> Any
catch (error_type = Any) (handler = x->x) =
catch self (error_type = Any) (handler = x->x) =
self.catch_primitive error_value->
case error_value.is_a error_type of
True -> handler error_value
@ -299,7 +299,7 @@ type Any
error = my_map.get "x"
error.map_error (_ -> Example_Error_Type "x is missing")
map_error : (Error -> Error) -> Any
map_error _ = self
map_error self _ = self
## Checks if `self` is an error.
@ -308,7 +308,7 @@ type Any
1.is_error
is_error : Boolean
is_error = False
is_error self = False
## Applies the provided function to `self` unless `self` is `Nothing`, which is
returned unchanged.
@ -321,7 +321,7 @@ type Any
10.map_nothing *2
map_nothing : (a -> b) -> b | Nothing
map_nothing f = case self of
map_nothing self f = case self of
Nothing -> Nothing
a -> f a
@ -342,7 +342,7 @@ type Any
y = 1 ^ 3
3 + y
<| : Any -> Any
<| ~argument = self argument
<| self ~argument = self argument
## Applies the function on the right hand side to the argument on the left.
@ -363,7 +363,7 @@ type Any
1 |> (* 2) |> (/ 100) |> .to_text
|> : (Any -> Any) -> Any
|> ~function = function self
|> self ~function = function self
## Composes two functions together, for `f << g` creating the function
composition `f ∘ g` (equivalent to `x -> f (g x)`).
@ -376,7 +376,7 @@ type Any
(+1 << *2) 2
<< : (Any -> Any) -> (Any -> Any) -> Any -> Any
<< ~that = x -> self (that x)
<< self ~that = x -> self (that x)
## Composes two functions together in the forward direction, for `f >> g`
creating the function composition `g ∘ f` (equivalent to `x -> g (f (x))`).
@ -389,7 +389,7 @@ type Any
(+1 >> *2) 2
>> : (Any -> Any) -> (Any -> Any) -> Any -> Any
>> ~that = x -> that (self x)
>> self ~that = x -> that (self x)
## UNSTABLE
ADVANCED
@ -408,4 +408,4 @@ type Any
2.to_default_visualization_data
to_default_visualization_data : Text
to_default_visualization_data = self.to_json.to_text
to_default_visualization_data self = self.to_json.to_text

View File

@ -21,7 +21,7 @@ type Array
[1,2,3].to_array.at 1
at : Integer -> Any
at index = @Builtin_Method "Array.at"
at self index = @Builtin_Method "Array.at"
## Set the cell at the specified index to the provided value, returning
the array.
@ -37,7 +37,7 @@ type Array
If index < 0 or index >= self.length, then this operation will result
in an Invalid_Array_Index_Error exception.
set_at : Integer -> Any -> Array
set_at index value = @Builtin_Method "Array.set_at"
set_at self index value = @Builtin_Method "Array.set_at"
## Gets the length of the array this.
@ -46,7 +46,7 @@ type Array
[1,2,3].to_array.length
length : Integer
length = @Builtin_Method "Array.length"
length self = @Builtin_Method "Array.length"
## Sorts the this array in place.
@ -60,14 +60,14 @@ type Array
[1,2,3].to_array.sort
sort : (Any -> Any -> Ordering) -> Nothing
sort comparator = @Builtin_Method "Array.sort"
sort self comparator = @Builtin_Method "Array.sort"
## Identity.
This method is implemented purely for completeness with the runtime's
primitive array protocol.
to_array : Array
to_array = @Builtin_Method "Array.to_array"
to_array self = @Builtin_Method "Array.to_array"
## UNSTABLE
ADVANCED
@ -83,7 +83,7 @@ type Array
[1, 2, 3, 4].to_array.to_default_visualization_data
to_default_visualization_data : Text
to_default_visualization_data =
to_default_visualization_data self =
Vector.Vector self . to_default_visualization_data
## Creates an array with length 0.

View File

@ -18,7 +18,7 @@ type Boolean
True == False
== : Boolean -> Boolean
== that = @Builtin_Method "Boolean.=="
== self that = @Builtin_Method "Boolean.=="
## Computes the logical and (conjunction) of two booleans.
@ -34,7 +34,7 @@ type Boolean
False && True
&& : Boolean -> Boolean
&& ~that = @Builtin_Method "Boolean.&&"
&& self ~that = @Builtin_Method "Boolean.&&"
## Computes the logical or (disjunction) of two booleans.
@ -50,7 +50,7 @@ type Boolean
True || False
|| : Boolean -> Boolean
|| ~that = @Builtin_Method "Boolean.||"
|| self ~that = @Builtin_Method "Boolean.||"
## Computes the logical negation of this.
@ -59,7 +59,20 @@ type Boolean
True.not
not : Boolean
not = @Builtin_Method "Boolean.not"
not self = @Builtin_Method "Boolean.not"
## Compares the two operands to determine the ordering of this with
respect to that.
Arguments:
- that: The operand to order this with respect to.
> Example
Computing the ordering of True and False
True.compare_to False
compare_to : Boolean -> Ordering
compare_to self that = @Builtin_Method "Boolean.compare_to"
## The if-then-else control flow operator that executes one of two branches
based on a conditional.
@ -76,7 +89,7 @@ type Boolean
if (27 % 3) == 0 then IO.println "Yes" else IO.println "No"
if_then_else : Any -> Any -> Any
if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else"
if_then_else self ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else"
## The if-then control flow operator that executes a branch if the condition
is true, and otherwise returns Nothing.
@ -92,7 +105,7 @@ type Boolean
if (27 % 3) == 0 then IO.println "Fizz"
if_then : Any -> Any | Nothing
if_then ~on_true = @Builtin_Method "Boolean.if_then"
if_then self ~on_true = @Builtin_Method "Boolean.if_then"
## The constructor for the value True.
@Builtin_Type

View File

@ -72,7 +72,7 @@ type Interval
example_contains = (Interval.inclusive 0.1 1) . contains 0.33
contains : Number -> Boolean
contains that = if self.start.n > self.end.n then False else
contains self that = if self.start.n > self.end.n then False else
case self.start of
Bound.Exclusive s -> (that > s) && case self.end of
Bound.Exclusive e -> that < e
@ -90,7 +90,7 @@ type Interval
example_is_empty = Interval.inclusive 0 0 . is_empty
is_empty : Boolean
is_empty = case self.start of
is_empty self = case self.start of
Bound.Exclusive s -> case self.end of
Bound.Exclusive e -> s >= e
Bound.Inclusive e -> s >= e
@ -107,5 +107,5 @@ type Interval
example_not_empty = Interval.inclusive 0 0.001 . not_empty
not_empty : Boolean
not_empty = self.is_empty.not
not_empty self = self.is_empty.not

View File

@ -101,7 +101,7 @@ type Json
format = (Vector.Vector (Book title=Text (Author name=Text year_of_birth=Number)))
json.into format
into : Any -> Any ! Marshalling_Error
into type_descriptor =
into self type_descriptor =
Panic.recover Any (Internal.into_helper type_descriptor self)
## Returns this Json object.
@ -109,7 +109,7 @@ type Json
This is a no-op on a JSON object, but is included to implement the
`to_json` interface.
to_json : Json
to_json = self
to_json self = self
## Renders this JSON into an RFC-8259 compliant text.
@ -121,7 +121,7 @@ type Json
example_to_text = Examples.json.to_text
to_text : Text
to_text = Internal.render_helper "" self
to_text self = Internal.render_helper "" self
## Recursively unwraps the JSON value into primitive values.
@ -132,7 +132,7 @@ type Json
example_unwrap = Json.Number 3 . unwrap
unwrap : Any
unwrap = case self of
unwrap self = case self of
Json.Array its -> its.map .unwrap
Json.Boolean b -> b
Json.Number n -> n
@ -151,7 +151,7 @@ type Parse_Error message
Converts the error to a display representation.
Parse_Error.to_display_text : Text
Parse_Error.to_display_text =
Parse_Error.to_display_text self =
"Parse error in parsing JSON: " + self.message.to_text + "."
## Gets the value associated with the given key in this object.
@ -169,7 +169,7 @@ Parse_Error.to_display_text =
example_get = Examples.json_object.get "title"
Object.get : Text -> Json ! No_Such_Field_Error
Object.get field = self.fields.get field . map_error case _ of
Object.get self field = self.fields.get field . map_error case _ of
Map.No_Value_For_Key_Error _ -> No_Such_Field_Error field
x -> x
@ -182,7 +182,7 @@ type No_Such_Field_Error field_name
Pretty prints the no such field error.
No_Such_Field_Error.to_display_text : Text
No_Such_Field_Error.to_display_text =
No_Such_Field_Error.to_display_text self =
"The field " + self.field_name.to_text + " is not present in this object."
## UNSTABLE
@ -221,7 +221,7 @@ type Marshalling_Error
Convert the marshalling error into a human-readable format.
to_display_text : Text
to_display_text = case self of
to_display_text self = case self of
Type_Mismatch_Error json format ->
json_text = Meta.get_simple_type_name json
format_text = Meta.get_simple_type_name format
@ -240,7 +240,7 @@ type Marshalling_Error
> Example
Convert a vector to JSON.
[1, 2, 3, 4].to_json
Any.to_json =
Any.to_json self =
m = Meta.meta self
case m of
Meta.Atom _ ->
@ -265,7 +265,7 @@ Any.to_json =
Ensure that the text "foo" is a JSON key.
"foo".to_json_key
Text.to_json_key : Text
Text.to_json_key = self
Text.to_json_key self = self
## Convert a boolean to JSON.
@ -273,7 +273,7 @@ Text.to_json_key = self
Convert `True` to JSON.
True.to_json
Base.Boolean.to_json : Boolean
Base.Boolean.to_json = Boolean self
Base.Boolean.to_json self = Boolean self
## Convert `Nothing` to JSON.
@ -281,5 +281,5 @@ Base.Boolean.to_json = Boolean self
Convert `Nothing` to JSON.
Nothing.to_json
Nothing.to_json : Null
Nothing.to_json = Null
Nothing.to_json self = Null

View File

@ -32,7 +32,7 @@ type Consumer
Arguments:
- v: The value to act upon.
on_value : Any -> Nothing
on_value v = case self.child_consumer . get of
on_value self v = case self.child_consumer . get of
Nil -> self.value . put v
cons -> cons.on_value v
@ -41,7 +41,7 @@ type Consumer
Closes the child consumer and either sets the current consumer to its
parent, or takes its returned value as the final result of parsing.
seal_child : Nothing
seal_child =
seal_child self =
child = self.child_consumer.get
val = child.seal
case child.parent of
@ -55,7 +55,7 @@ type Consumer
Consumes the `start_object` event.
on_start_object : Nothing
on_start_object =
on_start_object self =
parent = self.child_consumer . get
self.child_consumer . put (mk_object_consumer parent)
@ -66,19 +66,19 @@ type Consumer
Arguments:
- k: The key to act upon.
on_key : Text -> Nothing
on_key k = self.child_consumer . get . on_key k
on_key self k = self.child_consumer . get . on_key k
## PRIVATE
Consumes the `end_object` event.
on_end_object : Nothing
on_end_object = self.seal_child
on_end_object self = self.seal_child
## PRIVATE
Consumes the `start_array` event.
on_start_array : Nothing
on_start_array =
on_start_array self =
parent = self.child_consumer . get
self.child_consumer . put (mk_array_consumer parent)
@ -86,7 +86,7 @@ type Consumer
Consumes the `end_array` event.
on_end_array : Nothing
on_end_array = self.seal_child
on_end_array self = self.seal_child
## PRIVATE
@ -95,7 +95,7 @@ type Consumer
Arguments:
- n: The long value to process.
on_long : Integer -> Nothing
on_long n = self.on_value (Number n)
on_long self n = self.on_value (Number n)
## PRIVATE
@ -104,7 +104,7 @@ type Consumer
Arguments:
- n: The double value to process.
on_double : Decimal -> Nothing
on_double n = self.on_value (Number n)
on_double self n = self.on_value (Number n)
## PRIVATE
@ -113,25 +113,25 @@ type Consumer
Arguments:
- s: The string value to process.
on_string : Text -> Nothing
on_string s = self.on_value (String s)
on_string self s = self.on_value (String s)
## PRIVATE
Consumes the `true` event.
on_true : Nothing
on_true = self.on_value (Boolean True)
on_true self = self.on_value (Boolean True)
## PRIVATE
Consumes the `false` event.
on_false : Nothing
on_false = self.on_value (Boolean False)
on_false self = self.on_value (Boolean False)
## PRIVATE
Consumes the `null` event.
on_null : Nothing
on_null = self.on_value Null
on_null self = self.on_value Null
## PRIVATE
@ -153,13 +153,13 @@ type Array_Consumer
Arguments:
- v: The value to process.
on_value : Any -> Nothing
on_value v = self.builder.append v
on_value self v = self.builder.append v
## PRIVATE
Returns the final value built by this consumer.
seal : Array
seal =
seal self =
vec = self.builder.to_vector
Array vec
@ -184,7 +184,7 @@ type Object_Consumer
Arguments:
- k: The key to process.
on_key : Text -> Nothing
on_key k = self.last_key . put k
on_key self k = self.last_key . put k
## PRIVATE
@ -193,7 +193,7 @@ type Object_Consumer
Arguments:
- v: The value to process.
on_value : Any -> Nothing
on_value v =
on_value self v =
k = self.last_key . get
m = self.map . get
new_m = m.insert k v
@ -203,7 +203,7 @@ type Object_Consumer
Returns the final value built by this consumer.
seal : Object
seal =
seal self =
m = self.map . get
Object m

View File

@ -36,7 +36,7 @@ type List
example_length = Examples.list.length
length : Number
length = self.fold 0 (acc -> _ -> acc + 1)
length self = self.fold 0 (acc -> _ -> acc + 1)
## Combines all the elements of the list, by iteratively applying the
passed function with next elements of the list.
@ -58,7 +58,7 @@ type List
example_fold = Examples.list.fold 0 (+)
fold : Any -> (Any -> Any -> Any) -> Any
fold init f =
fold self init f =
go acc list = case list of
Nil -> acc
Cons h t -> @Tail_Call go (f acc h) t
@ -79,7 +79,7 @@ type List
example_exists = Examples.list.exists (> 5)
exists : (Any -> Boolean) -> Boolean
exists predicate =
exists self predicate =
go list = case list of
Nil -> False
Cons h t -> if predicate h then True else
@ -104,7 +104,7 @@ type List
example_any = Examples.list.any (> 5)
any : (Any -> Boolean) -> Boolean
any predicate = self.exists predicate
any self predicate = self.exists predicate
## Checks whether a predicate holds for all elements in this list.
@ -120,7 +120,7 @@ type List
example_all = Examples.list.all (> 0)
all : (Any -> Boolean) -> Boolean
all predicate = self.fold True (l -> r -> l && predicate r)
all self predicate = self.fold True (l -> r -> l && predicate r)
## Checks whether this list contains a given value as an element.
@ -134,7 +134,7 @@ type List
example_contains = Examples.list.contains 3
contains : Any -> Boolean
contains elem = self.exists ix-> ix == elem
contains self elem = self.exists ix-> ix == elem
## Checks if this list is empty.
@ -145,7 +145,7 @@ type List
example_empty = Examples.list.is_empty
is_empty : Boolean
is_empty = self.length == 0
is_empty self = self.length == 0
## Checks if the list is not empty.
@ -156,7 +156,7 @@ type List
example_not_empty = Examples.list.not_empty
not_empty : Boolean
not_empty = self.is_empty.not
not_empty self = self.is_empty.not
## Selects all elements of this list which satisfy a predicate.
@ -172,7 +172,7 @@ type List
example_filter = Examples.list.filter (< 3)
filter : (Any -> Boolean) -> List
filter predicate =
filter self predicate =
case self of
Cons a b ->
rest = b.filter predicate
@ -192,7 +192,7 @@ type List
example_map = Examples.list.map +1
map : (Any -> Any) -> List
map f = case self of
map self f = case self of
Nil -> Nil
Cons h t ->
res = Cons (f h) Nil
@ -214,7 +214,7 @@ type List
example_each = Examples.list.each IO.println
each : (Any -> Any) -> Nothing
each f =
each self f =
go list = case list of
Nil -> Nothing
Cons h t ->
@ -233,7 +233,7 @@ type List
example_reverse = Examples.list.reverse
reverse : List
reverse = self.fold Nil (l -> el -> Cons el l)
reverse self = self.fold Nil (l -> el -> Cons el l)
## Creates a new list with the first `count` elements at the start of `self`
removed.
@ -248,7 +248,7 @@ type List
example_drop_start = Examples.list.drop_start 1
drop_start : Integer -> List
drop_start count = if count <= 0 then self else case self of
drop_start self count = if count <= 0 then self else case self of
Cons _ b -> b.drop_start count-1
Nil -> Nil
@ -265,7 +265,7 @@ type List
example_take_start = Examples.list.take_start 2
take_start : Integer -> List
take_start count = if count <= 0 then Nil else case self of
take_start self count = if count <= 0 then Nil else case self of
Cons a b -> Cons a (b.take_start count-1)
Nil -> Nil
@ -278,7 +278,7 @@ type List
example_head = Examples.list.x
head : Any ! Empty_Error
head = case self of
head self = case self of
Cons a _ -> a
Nil -> Error.throw Empty_Error
@ -291,7 +291,7 @@ type List
example_tail = Examples.list.tail
tail : List ! Empty_Error
tail = case self of
tail self = case self of
Cons _ b -> b
Nil -> Error.throw Empty_Error
@ -304,7 +304,7 @@ type List
example_init = Examples.list.init
init : List ! Empty_Error
init =
init self =
init' x y = case y of
Nil -> Nil
Cons a b -> Cons x (init' a b)
@ -321,7 +321,7 @@ type List
example_last = Examples.list.last
last : Any ! Empty_Error
last = case self.fold Nothing (_ -> r -> r) of
last self = case self.fold Nothing (_ -> r -> r) of
Nothing -> Error.throw Empty_Error
a -> a
@ -334,7 +334,7 @@ type List
example_first = Examples.list.first
first : Any ! Empty_Error
first = self.head
first self = self.head
## Get all elements from the list except the first.
@ -345,7 +345,7 @@ type List
example_rest = Examples.list.rest
rest : List ! Empty_Error
rest = self.tail
rest self = self.tail
## UNSTABLE
@ -356,7 +356,7 @@ type Empty_Error
Pretty prints the empty error.
Empty_Error.to_display_text : Text
Empty_Error.to_display_text = "The List is empty."
Empty_Error.to_display_text self = "The List is empty."
## PRIVATE
A helper for the `map` function.

View File

@ -314,7 +314,7 @@ type Locale
example_language = Locale.default.language
language : Text | Nothing
language =
language self =
lang = self.java_locale.getLanguage
if lang.is_empty then Nothing else lang
@ -327,7 +327,7 @@ type Locale
example_country = Locale.default.country
country : Text | Nothing
country =
country self =
place = self.java_locale.getCountry
if place.is_empty then Nothing else place
@ -340,7 +340,7 @@ type Locale
example_variant = Locale.default.variant
variant : Text | Nothing
variant =
variant self =
var = self.java_locale.getVariant
if var.is_empty then Nothing else var
@ -354,7 +354,7 @@ type Locale
example_display_language = Locale.default.display_language
display_language : Text | Nothing
display_language =
display_language self =
disp = self.java_locale.getDisplayLanguage
if disp.is_empty then Nothing else disp
@ -368,7 +368,7 @@ type Locale
example_display_country = Locale.default.display_country
display_country : Text | Nothing
display_country =
display_country self =
disp = self.java_locale.getDisplayCountry
if disp.is_empty then Nothing else disp
@ -382,7 +382,7 @@ type Locale
example_display_variant = Locale.default.display_variant
display_variant : Text | Nothing
display_variant =
display_variant self =
disp = self.java_locale.getDisplayVariant
if disp.is_empty then Nothing else disp
@ -395,7 +395,7 @@ type Locale
example_to_text = Locale.default.to_text
to_text : Text | Nothing
to_text = self.java_locale.toLanguageTag
to_text self = self.java_locale.toLanguageTag
## A Locale to Json conversion
@ -406,7 +406,7 @@ type Locale
example_to_json = Locale.default.to_json
to_json : Json.Object
to_json =
to_json self =
b = Vector.new_builder
b.append ["type", "Locale"]
if self.language.is_nothing.not then b.append ["language", self.language]
@ -416,7 +416,7 @@ type Locale
## Compares two locales for equality.
== : Any -> Boolean
== other = case other of
== self other = case other of
Locale other_java_locale -> self.java_locale.equals other_java_locale
_ -> False

View File

@ -73,7 +73,7 @@ type Map
example_is_empty = Examples.map.is_empty
is_empty : Boolean
is_empty = case self of
is_empty self = case self of
Bin _ _ _ _ _ -> False
Tip -> True
@ -87,7 +87,7 @@ type Map
example_not_empty = Examples.map.not_empty
not_empty : Boolean
not_empty = self.is_empty.not
not_empty self = self.is_empty.not
## Returns the number of entries in this map.
@ -99,7 +99,7 @@ type Map
example_size = Examples.map.size
size : Integer
size = case self of
size self = case self of
Bin s _ _ _ _ -> s
Tip -> 0
@ -115,7 +115,7 @@ type Map
example_to_vector = Examples.map.to_vector
to_vector : Vector.Vector Any
to_vector =
to_vector self =
builder = Vector.new_builder
to_vector_with_builder m = case m of
Bin _ k v l r ->
@ -138,7 +138,7 @@ type Map
example_to_text = Examples.map.to_text
to_text : Text
to_text = self.to_vector.to_text
to_text self = self.to_vector.to_text
## Checks if this map is equal to another map.
@ -158,7 +158,7 @@ type Map
other = Map.empty . insert 1 "one" . insert 3 "three" . insert 5 "five"
Examples.map == other
== : Map -> Boolean
== that = self.to_vector == that.to_vector
== self that = self.to_vector == that.to_vector
## Inserts a key-value mapping into this map, overriding any existing
instance of `key` with the new `value`.
@ -175,7 +175,7 @@ type Map
example_insert = Examples.map.insert 7 "seven"
insert : Any -> Any -> Map
insert key value = Internal.insert self key value
insert self key value = Internal.insert self key value
## Gets the value associated with `key` in this map, or throws a
`No_Value_For_Key_Error` if `key` is not present.
@ -191,7 +191,7 @@ type Map
example_get = Examples.map.get 1
get : Any -> Any ! No_Value_For_Key_Error
get key =
get self key =
go map = case map of
Tip -> Error.throw (No_Value_For_Key_Error key)
Bin _ k v l r ->
@ -216,7 +216,7 @@ type Map
example_get_or_else = Examples.map.get_or_else 2 "zero"
get_or_else : Any -> Any -> Any
get_or_else key ~other =
get_or_else self key ~other =
self.get key . catch No_Value_For_Key_Error (_ -> other)
## Transforms the map's keys and values to create a new map.
@ -234,7 +234,7 @@ type Map
example_transform =
Examples.map.transform (k -> v -> [k.to_text, v + "_word"])
transform : (Any -> Any -> [Any, Any]) -> Map
transform function =
transform self function =
func_pairs = p -> function (p.at 0) (p.at 1)
vec_transformed = self.to_vector.map func_pairs
from_vector vec_transformed
@ -253,7 +253,7 @@ type Map
example_map = Examples.map.map (+ "_word")
map : (Any -> Any) -> Map
map function =
map self function =
kv_func = _ -> function
self.map_with_key kv_func
@ -273,7 +273,7 @@ type Map
example_map_with_key =
Examples.map.map_with_key (k -> v -> k.to_text + "-" + v)
map_with_key : (Any -> Any -> Any) -> Map
map_with_key function =
map_with_key self function =
go map = case map of
Bin s k v l r ->
Bin s k (function k v) (go l) (go r)
@ -294,7 +294,7 @@ type Map
example_map_keys = Examples.map.map_keys *2
map_keys : (Any -> Any) -> Map
map_keys function =
map_keys self function =
trans_function = k -> v -> [function k, v]
self.transform trans_function
@ -315,7 +315,7 @@ type Map
example_each = Examples.map.each IO.println
each : (Any -> Any) -> Nothing
each function =
each self function =
kv_func = _ -> function
self.each_with_key kv_func
@ -338,7 +338,7 @@ type Map
IO.println k
IO.println v
each_with_key : (Any -> Any -> Any) -> Nothing
each_with_key function =
each_with_key self function =
go map = case map of
Bin _ k v l r ->
go l
@ -362,7 +362,7 @@ type Map
example_fold = Examples.map.fold 0 (l -> r -> Math.max l r.length)
fold : Any -> (Any -> Any -> Any) -> Any
fold init function =
fold self init function =
go map init = case map of
Bin _ _ v l r ->
y = go l init
@ -387,7 +387,7 @@ type Map
example_fold_with_key =
Examples.map.fold_with_key "" (l -> k -> v -> l + k.to_text + v)
fold_with_key : Any -> (Any -> Any -> Any -> Any) -> Any
fold_with_key init function =
fold_with_key self init function =
go map init = case map of
Bin _ k v l r ->
y = go l init
@ -406,7 +406,7 @@ type Map
example_keys = Examples.map.keys
keys : Vector
keys =
keys self =
builder = Vector.new_builder
to_vector_with_builder m = case m of
Bin _ k _ l r ->
@ -428,7 +428,7 @@ type Map
example_values = Examples.map.values
values : Vector
values =
values self =
builder = Vector.new_builder
to_vector_with_builder m = case m of
Bin _ _ v l r ->
@ -443,7 +443,7 @@ type Map
## Get a key value pair of the lowest key in the map.
If the map is empty, returns Nothing.
first : Pair
first =
first self =
first p m = case m of
Bin _ k v l _ -> @Tail_Call first (Pair k v) l
Tip -> p
@ -452,7 +452,7 @@ type Map
## Get a key value pair of the highest key in the map.
If the map is empty, returns Nothing.
last : Pair
last =
last self =
last p m = case m of
Bin _ k v _ r -> @Tail_Call last (Pair k v) r
Tip -> p
@ -470,6 +470,6 @@ type No_Value_For_Key_Error key
Converts the error into a human-readable representation.
No_Value_For_Key_Error.to_display_text : Text
No_Value_For_Key_Error.to_display_text =
No_Value_For_Key_Error.to_display_text self =
"The map contained no value for the key " + self.key.to_text + "."

View File

@ -35,7 +35,7 @@ type Maybe
example_maybe = Maybe.Some 2 . maybe 0 *2
maybe : Any -> (Any -> Any) -> Any
maybe ~default function = case self of
maybe self ~default function = case self of
Nothing -> default
Some val -> function val
@ -48,4 +48,4 @@ type Maybe
example_is_some = Maybe.Some "yes!" . is_some
is_some : Boolean
is_some = self.is_nothing.not
is_some self = self.is_nothing.not

View File

@ -19,5 +19,5 @@ from Standard.Base.Data.Noise.Generator import all
Deterministically perturb the input number 1.
1.noise
Number.noise : Interval -> Generator -> Any
Number.noise (interval = Interval.exclusive 0 1) gen=Deterministic_Random =
Number.noise self (interval = Interval.exclusive 0 1) gen=Deterministic_Random =
gen.step self interval

View File

@ -30,7 +30,7 @@ type Generator
The return type may be chosen freely by the generator implementation, as
it usually depends on the generator and its intended use.
step : Number -> Interval -> Any
step _ _ = unimplemented "Only intended to demonstrate an interface."
step self _ _ = unimplemented "Only intended to demonstrate an interface."
## A noise generator that implements a seeded deterministic random peterbation
of the input.
@ -59,7 +59,7 @@ type Deterministic_Random
example_det_random = Deterministic_Random.step 1 (Interval.inclusive 0 1)
step : Number -> Interval -> Number
step input interval =
step self input interval =
max_long = Long.MAX_VALUE
seed = input.floor % max_long
gen = Random.new seed

View File

@ -37,7 +37,7 @@ type Number
10 + 15
+ : Number -> Number
+ that = @Builtin_Method "Integer.+"
+ self that = @Builtin_Method "Integer.+"
## ALIAS Subtract
@ -51,7 +51,7 @@ type Number
2 - 5
- : Number -> Number
- that = @Builtin_Method "Integer.-"
- self that = @Builtin_Method "Integer.-"
## ALIAS Multiply
@ -68,7 +68,7 @@ type Number
3 * 5
* : Number -> Number
* that = @Builtin_Method "Integer.*"
* self that = @Builtin_Method "Integer.*"
## ALIAS Divide
@ -85,7 +85,7 @@ type Number
10 / 4
/ : Number -> Number
/ that = @Builtin_Method "Integer./"
/ self that = @Builtin_Method "Integer./"
## ALIAS Power
@ -99,7 +99,7 @@ type Number
2^3
^ : Number -> Number
^ that = @Builtin_Method "Integer.^"
^ self that = @Builtin_Method "Integer.^"
## ALIAS Inverse Sine
@ -112,7 +112,7 @@ type Number
1.asin
asin : Decimal
asin = Math.asin self.to_decimal
asin self = Math.asin self.to_decimal
## ALIAS Inverse Cosine
@ -125,7 +125,7 @@ type Number
1.acos
acos : Decimal
acos = Math.acos self.to_decimal
acos self = Math.acos self.to_decimal
## ALIAS Inverse Tangent
@ -138,7 +138,7 @@ type Number
1.atan
atan : Decimal
atan = Math.atan self.to_decimal
atan self = Math.atan self.to_decimal
## Computes the argument (angle) in the conversion from cartesian
to polar coordinates, taking `self` as the x coordinate.
@ -153,7 +153,7 @@ type Number
1.atan_2 2
atan_2 : Number -> Decimal
atan_2 y = Math.atan2 self.to_decimal y.to_decimal
atan_2 self y = Math.atan2 self.to_decimal y.to_decimal
## ALIAS Sine
@ -164,7 +164,7 @@ type Number
2.sin
sin : Decimal
sin = Math.sin self.to_decimal
sin self = Math.sin self.to_decimal
## ALIAS Cosine
@ -175,7 +175,7 @@ type Number
2.cos
cos : Decimal
cos = Math.cos self.to_decimal
cos self = Math.cos self.to_decimal
## ALIAS Tangent
@ -186,7 +186,7 @@ type Number
2.tan
tan : Decimal
tan = Math.tan self.to_decimal
tan self = Math.tan self.to_decimal
## Computes the hyperbolic sine function.
@ -195,7 +195,7 @@ type Number
1.sinh
sinh : Decimal
sinh = Math.sinh self.to_decimal
sinh self = Math.sinh self.to_decimal
## Computes the hyperbolic cosine function.
@ -204,7 +204,7 @@ type Number
1.cosh
cosh : Decimal
cosh = Math.cosh self.to_decimal
cosh self = Math.cosh self.to_decimal
## Computes the hyperbolic tangent function.
@ -213,7 +213,7 @@ type Number
1.tanh
tanh : Decimal
tanh = Math.tanh self.to_decimal
tanh self = Math.tanh self.to_decimal
## ALIAS Exponential
@ -225,7 +225,7 @@ type Number
4.exp
exp : Decimal
exp = Math.exp self.to_decimal
exp self = Math.exp self.to_decimal
## ALIAS Natural Logarithm
@ -236,7 +236,7 @@ type Number
2.ln
ln : Decimal
ln = Math.log self.to_decimal
ln self = Math.log self.to_decimal
## ALIAS Square Root
@ -247,7 +247,7 @@ type Number
8.sqrt
sqrt : Decimal
sqrt = Math.sqrt self.to_decimal
sqrt self = Math.sqrt self.to_decimal
## ALIAS Logarithm
@ -261,7 +261,7 @@ type Number
4.log 2
log : Number -> Decimal
log base = self.ln / base.ln
log self base = self.ln / base.ln
## UNSTABLE This API is not user-friendly and will be improved in the future.
@ -276,7 +276,7 @@ type Number
5.format "%x"
format : Text -> Text
format fmt = String.format fmt self
format self fmt = String.format fmt self
## Checks equality of numbers, using an `epsilon` value.
@ -290,7 +290,7 @@ type Number
1.equals 1.0000001 epsilon=0.001
equals : Number -> Number -> Boolean
equals that epsilon=0.0 =
equals self that epsilon=0.0 =
(self == that) || ((self - that).abs <= epsilon)
## Returns the smaller value of `self` and `that`.
@ -308,7 +308,7 @@ type Number
2.min 5
min : Number -> Number
min that = if self < that then self else that
min self that = if self < that then self else that
## Returns the larger value of `self` and `that`.
@ -325,7 +325,7 @@ type Number
2.max 5
max : Number -> Number
max that = if self > that then self else that
max self that = if self > that then self else that
## Number to JSON conversion.
@ -334,7 +334,7 @@ type Number
8.to_json
to_json : Json.Number
to_json = Json.Number self
to_json self = Json.Number self
## A constant holding the floating-point positive infinity.
positive_infinity : Decimal
@ -353,13 +353,13 @@ type Number
This is needed, because the NaN value will return `False` even when being
compared with itself, so `x == Number.nan` would not work.
is_nan : Boolean
is_nan = case self of
is_nan self = case self of
Decimal -> Double.isNaN self
_ -> False
## Returns the sign of the number.
signum : Integer
signum =
signum self =
if self > 0 then 1 else
if self < 0 then -1 else 0
@ -388,7 +388,7 @@ type Decimal
10.1 + 15
+ : Number -> Number
+ that = @Builtin_Method "Decimal.+"
+ self that = @Builtin_Method "Decimal.+"
## Subtract an arbitrary number from this.
@ -400,7 +400,7 @@ type Decimal
2.78 - 5
- : Number -> Number
- that = @Builtin_Method "Decimal.-"
- self that = @Builtin_Method "Decimal.-"
## Multiply a decimal by an arbitrary number.
@ -415,7 +415,7 @@ type Decimal
5.27 * 3
* : Number -> Number
* that = @Builtin_Method "Decimal.*"
* self that = @Builtin_Method "Decimal.*"
## Divides a decimal by an arbitrary number.
@ -430,7 +430,7 @@ type Decimal
10 / 4.5
/ : Number -> Number
/ that = @Builtin_Method "Decimal./"
/ self that = @Builtin_Method "Decimal./"
## Computes the remainder when dividing this by that.
@ -450,7 +450,7 @@ type Decimal
10.5 % 1.0 == 0.5
% : Number -> Number ! Arithmetic_Error
% that = @Builtin_Method "Decimal.%"
% self that = @Builtin_Method "Decimal.%"
## Compute the result of raising this to the power that.
@ -462,7 +462,7 @@ type Decimal
2.2^3
^ : Number -> Number
^ that = @Builtin_Method "Decimal.^"
^ self that = @Builtin_Method "Decimal.^"
## Compares this and that for equality.
@ -474,7 +474,7 @@ type Decimal
7 == 2.1
== : Number -> Boolean
== that = @Builtin_Method "Decimal.=="
== self that = @Builtin_Method "Decimal.=="
## Checks if this is greater than that.
@ -486,7 +486,7 @@ type Decimal
10 > 7.3
> : Number -> Boolean
> that = @Builtin_Method "Decimal.>"
> self that = @Builtin_Method "Decimal.>"
## Checks if this is greater than or equal to thatthat.
@ -498,7 +498,7 @@ type Decimal
10 >= 7.3
>= : Number -> Boolean
>= that = @Builtin_Method "Decimal.>="
>= self that = @Builtin_Method "Decimal.>="
## Checks if this is less than that.
@ -510,7 +510,7 @@ type Decimal
10 < 7.3
< : Number -> Boolean
< that = @Builtin_Method "Decimal.<"
< self that = @Builtin_Method "Decimal.<"
## Checks if this is less than or equal to thatthat.
@ -522,7 +522,7 @@ type Decimal
10.4 <= 7
<= : Number -> Boolean
<= that = @Builtin_Method "Decimal.<="
<= self that = @Builtin_Method "Decimal.<="
## Computes the absolute value of this.
@ -534,7 +534,7 @@ type Decimal
-10.63.abs
abs : Decimal
abs = @Builtin_Method "Decimal.abs"
abs self = @Builtin_Method "Decimal.abs"
## Computes the nearest integer above this number.
@ -545,7 +545,7 @@ type Decimal
4.736.ceil
ceil : Integer
ceil = @Builtin_Method "Integer.ceil"
ceil self = @Builtin_Method "Integer.ceil"
## Compares the two operands to determine the ordering of this with
respect to that.
@ -558,7 +558,7 @@ type Decimal
1.732.compare_to 4
compare_to : Number -> Ordering
compare_to that = @Builtin_Method "Decimal.compare_to"
compare_to self that = @Builtin_Method "Decimal.compare_to"
## Computes the nearest integer below this decimal.
@ -569,7 +569,7 @@ type Decimal
4.323.floor
floor : Integer
floor = @Builtin_Method "Decimal.floor"
floor self = @Builtin_Method "Decimal.floor"
## Compute the negation of this.
@ -578,7 +578,7 @@ type Decimal
5.1.negate
negate : Decimal
negate = @Builtin_Method "Decimal.negate"
negate self = @Builtin_Method "Decimal.negate"
## Convert this to a decimal.
@ -590,7 +590,7 @@ type Decimal
5.0.to_decimal
to_decimal : Decimal
to_decimal = @Builtin_Method "Decimal.to_decimal"
to_decimal self = @Builtin_Method "Decimal.to_decimal"
## ALIAS From Text
@ -641,7 +641,7 @@ type Integer
10 + 15
+ : Number -> Number
+ that = @Builtin_Method "Integer.+"
+ self that = @Builtin_Method "Integer.+"
## Subtract an arbitrary number from this.
@ -653,7 +653,7 @@ type Integer
2 - 5
- : Number -> Number
- that = @Builtin_Method "Integer.-"
- self that = @Builtin_Method "Integer.-"
## Multiply an integer by an arbitrary number.
@ -668,7 +668,7 @@ type Integer
3 * 5
* : Number -> Number
* that = @Builtin_Method "Integer.*"
* self that = @Builtin_Method "Integer.*"
## Divides an integer by an arbitrary number.
@ -683,7 +683,7 @@ type Integer
10 / 4
/ : Number -> Number
/ that = @Builtin_Method "Integer./"
/ self that = @Builtin_Method "Integer./"
## Computes the remainder when dividing this by that.
@ -700,7 +700,7 @@ type Integer
10 % 3
% : Number -> Number ! Arithmetic_Error
% that = @Builtin_Method "Integer.%"
% self that = @Builtin_Method "Integer.%"
## Compute the result of raising this to the power that.
@ -712,7 +712,7 @@ type Integer
2^3
^ : Number -> Number
^ that = @Builtin_Method "Integer.^"
^ self that = @Builtin_Method "Integer.^"
## Compares this and that for equality.
@ -724,7 +724,7 @@ type Integer
7 == 2
== : Number -> Boolean
== that = @Builtin_Method "Integer.=="
== self that = @Builtin_Method "Integer.=="
## Checks if this is greater than that.
@ -736,7 +736,7 @@ type Integer
10 > 7
> : Number -> Boolean
> that = @Builtin_Method "Integer.>"
> self that = @Builtin_Method "Integer.>"
## Checks if this is greater than or equal to thatthat.
@ -748,7 +748,7 @@ type Integer
10 >= 7
>= : Number -> Boolean
>= that = @Builtin_Method "Integer.>="
>= self that = @Builtin_Method "Integer.>="
## Checks if this is less than that.
@ -760,7 +760,7 @@ type Integer
10 < 7
< : Number -> Boolean
< that = @Builtin_Method "Integer.<"
< self that = @Builtin_Method "Integer.<"
## Checks if this is less than or equal to thatthat.
@ -772,7 +772,7 @@ type Integer
10 <= 7
<= : Number -> Boolean
<= that = @Builtin_Method "Integer.<="
<= self that = @Builtin_Method "Integer.<="
## Computes the absolute value of this.
@ -784,7 +784,7 @@ type Integer
-10.abs
abs : Integer
abs = @Builtin_Method "Integer.abs"
abs self = @Builtin_Method "Integer.abs"
## Computes the nearest integer above this integer.
@ -796,7 +796,7 @@ type Integer
4.ceil
ceil : Integer
ceil = @Builtin_Method "Integer.ceil"
ceil self = @Builtin_Method "Integer.ceil"
## Compares the two operands to determine the ordering of this with
respect to that.
@ -809,7 +809,7 @@ type Integer
1.compare_to 4
compare_to : Number -> Ordering
compare_to that = @Builtin_Method "Integer.compare_to"
compare_to self that = @Builtin_Method "Integer.compare_to"
## Computes the integer division of this by that.
@ -825,7 +825,7 @@ type Integer
10.div 3
div : Integer -> Number ! Arithmetic_Error
div that = @Builtin_Method "Integer.div"
div self that = @Builtin_Method "Integer.div"
## Computes the nearest integer below this integer.
@ -837,7 +837,7 @@ type Integer
4.floor
floor : Integer
floor = @Builtin_Method "Integer.floor"
floor self = @Builtin_Method "Integer.floor"
## Compute the negation of this.
@ -846,7 +846,7 @@ type Integer
5.negate
negate : Integer
negate = @Builtin_Method "Integer.negate"
negate self = @Builtin_Method "Integer.negate"
## Convert this to a decimal.
@ -855,7 +855,7 @@ type Integer
5.to_decimal
to_decimal : Decimal
to_decimal = @Builtin_Method "Integer.to_decimal"
to_decimal self = @Builtin_Method "Integer.to_decimal"
## Computes the bitwise and (conjunction) operation between this and
that.
@ -871,7 +871,7 @@ type Integer
2_01101101.bit_and 2_11110000
bit_and : Integer -> Integer
bit_and that = @Builtin_Method "Integer.bit_and"
bit_and self that = @Builtin_Method "Integer.bit_and"
## Computes the bitewise compliment of this.
@ -882,7 +882,7 @@ type Integer
2_0110.bit_not
bit_not : Integer
bit_not = @Builtin_Method "Integer.bit_not"
bit_not self = @Builtin_Method "Integer.bit_not"
## Computes the bitwise or (disjunction) operation between this and
that.
@ -898,7 +898,7 @@ type Integer
2_01101101.bit_or 2_11110000
bit_or : Integer -> Integer
bit_or that = @Builtin_Method "Integer.bit_or"
bit_or self that = @Builtin_Method "Integer.bit_or"
## Computes the bitwise exclusive or between this and that.
@ -913,7 +913,7 @@ type Integer
2_01101101.bit_xor 2_11110000
bit_xor : Integer -> Integer
bit_xor that = @Builtin_Method "Integer.bit_xor"
bit_xor self that = @Builtin_Method "Integer.bit_xor"
## Shifts the bits of this by the amount that.
@ -932,7 +932,7 @@ type Integer
1.bit_shift 4
bit_shift : Integer -> Integer ! Arithmetic_Error
bit_shift that = @Builtin_Method "Integer.bit_shift"
bit_shift self that = @Builtin_Method "Integer.bit_shift"
## Performs a left-wise bit shift on the bits of this.
@ -951,7 +951,7 @@ type Integer
1.bit_shift_l 4
bit_shift_l : Integer -> Integer ! Arithmetic_Error
bit_shift_l that = @Builtin_Method "Integer.bit_shift_l"
bit_shift_l self that = @Builtin_Method "Integer.bit_shift_l"
## Performs a right-wise bit shift on the bits of this.
@ -970,7 +970,7 @@ type Integer
1.bit_shift_r 4
bit_shift_r : Integer -> Integer ! Arithmetic_Error
bit_shift_r that = @Builtin_Method "Integer.bpit_shift_r"
bit_shift_r self that = @Builtin_Method "Integer.bit_shift_r"
## ALIAS From Text

View File

@ -41,7 +41,7 @@ type Ordering
example_to_sign = Ordering.Equal.to_sign
to_sign : Integer
to_sign = case self of
to_sign self = case self of
Less -> -1
Greater -> 1
Equal -> 0

View File

@ -21,6 +21,6 @@ type Sort_Direction
## Convert into the sign of the direction
to_sign : Integer
to_sign = case self of
to_sign self = case self of
Ascending -> 1
Descending -> -1

View File

@ -21,5 +21,5 @@ type Pair
(Pair 1 2).map (+1) == (Pair 2 3)
map : (Any -> Any) -> Pair
map fun =
map self fun =
Pair (fun self.first) (fun self.second)

View File

@ -25,7 +25,7 @@ type Range
10.down_to 0 . with_step 2 . to_vector == [10, 8, 6, 4, 2]
with_step : Integer -> Range
with_step new_step = case new_step of
with_step self new_step = case new_step of
Integer ->
if new_step == 0 then throw_zero_step_error else
if new_step < 0 then Error.throw (Illegal_Argument_Error "The step should be positive. A decreasing sequence will remain decreasing after updating it with positive step, as this operation only sets the magnitude without changing the sign.") else
@ -36,7 +36,7 @@ type Range
## Returns the last element that is included within the range or `Nothing`
if the range is empty.
last : Integer | Nothing
last = if self.is_empty then Nothing else case self.step > 0 of
last self = if self.is_empty then Nothing else case self.step > 0 of
True ->
diff = self.end - self.start
rem = diff % self.step
@ -53,7 +53,7 @@ type Range
0.up_to 100 . length
length : Number
length = case self.last of
length self = case self.last of
Nothing -> 0
last -> ((last - self.start) . div self.step) + 1
@ -64,7 +64,7 @@ type Range
0.up_to 100 . is_empty
is_empty : Boolean
is_empty = if self.step > 0 then self.end <= self.start else
is_empty self = if self.step > 0 then self.end <= self.start else
if self.step < 0 then self.start <= self.end else
throw_zero_step_error
@ -75,7 +75,7 @@ type Range
0.up_to 100 . not_empty
not_empty : Boolean
not_empty = self.is_empty.not
not_empty self = self.is_empty.not
## Applies a function to each element in the range, producing a vector of
results.
@ -89,7 +89,7 @@ type Range
1.up_to 10 . map (*2)
map : (Number -> Any) -> Vector Any
map function =
map self function =
Vector.new self.length (i -> function (self.start + i*self.step))
## Returns a vector of all elements of this range which satisfy a predicate.
@ -104,7 +104,7 @@ type Range
(0.up_to 7).filter (> 3)
filter : (Any -> Boolean) -> Vector Any
filter predicate =
filter self predicate =
builder = self.fold Vector.new_builder builder-> elem->
if predicate elem then builder.append elem else builder
builder.to_vector
@ -118,7 +118,7 @@ type Range
To print all the numbers from 1 to 10 use:
1.up_to 11 . each IO.println
each : (Number -> Any) -> Nothing
each function =
each self function =
go end_condition current =
if end_condition current self.end then Nothing else
function current
@ -146,7 +146,7 @@ type Range
0.up_to 100 . with_step 2 . fold 0 (+)
fold : Any -> (Any -> Number -> Any) -> Any
fold init function =
fold self init function =
go end_condition acc current =
if end_condition current self.end then acc else
new_acc = function acc current
@ -167,7 +167,7 @@ type Range
10.up_to 100 . all (> 5)
all : (Number -> Boolean) -> Boolean
all predicate = self . exists (predicate >> .not) . not
all self predicate = self . exists (predicate >> .not) . not
## Checks whether `predicate` is satisfied for any number in this range.
@ -181,7 +181,7 @@ type Range
1.up_to 100 . exists (> 10)
exists : (Number -> Boolean) -> Boolean
exists predicate = self.find predicate . is_nothing . not
exists self predicate = self.find predicate . is_nothing . not
## Checks whether `predicate` is satisfied for any number in this range.
@ -195,7 +195,7 @@ type Range
1.up_to 100 . any (> 10)
any : (Number -> Boolean) -> Boolean
any predicate = self.exists predicate
any self predicate = self.exists predicate
## Gets the first index when `predicate` is satisfied this range.
If no index satisfies the predicate, return Nothing
@ -210,7 +210,7 @@ type Range
1.up_to 100 . find i->(i%2==0 && i%3==0 && i%5==0)
find : (Integer -> Boolean) -> Integer | Nothing
find predicate =
find self predicate =
go end_condition current =
if end_condition current self.end then Nothing else
if predicate current then current else
@ -226,7 +226,7 @@ type Range
1.up_to 6 . to_vector
to_vector : Vector.Vector
to_vector = self.map x->x
to_vector self = self.map x->x
## Checks if the range contains the specified value.
@ -236,7 +236,7 @@ type Range
vec = ["A", "B", "C", "D", "E"]
0.up_to vec.length . contains 3
contains : Integer -> Boolean
contains value = case value of
contains self value = case value of
Integer ->
if self.step > 0 then (value >= self.start) && (value < self.end) && (((value - self.start) % self.step) == 0) else
if self.step < 0 then (value <= self.start) && (value > self.end) && (((self.start - value) % (-self.step)) == 0) else
@ -260,7 +260,7 @@ type Range
0.up_to 5
Integer.up_to : Integer -> Range
Integer.up_to n = case n of
Integer.up_to self n = case n of
Integer -> Range self n
_ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.")
@ -276,7 +276,7 @@ Integer.up_to n = case n of
5.down_to 0
Integer.down_to : Integer -> Range
Integer.down_to n = case n of
Integer.down_to self n = case n of
Integer -> Range self n -1
_ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.")

View File

@ -55,7 +55,7 @@ type Fitted_Model
## Display the fitted line.
to_text : Text
to_text =
to_text self =
equation = case self of
Fitted_Linear_Model slope intercept _ -> slope.to_text + " * X + " + intercept.to_text
Fitted_Exponential_Model a b _ -> a.to_text + " * (" + b.to_text + " * X).exp"
@ -65,7 +65,7 @@ type Fitted_Model
## Use the model to predict a value.
predict : Number -> Number
predict x = case self of
predict self x = case self of
Fitted_Linear_Model slope intercept _ -> slope * x + intercept
Fitted_Exponential_Model a b _ -> a * (b * x).exp
Fitted_Logarithmic_Model a b _ -> a * x.ln + b
@ -101,7 +101,7 @@ type Fit_Error message
Converts the `Fit_Error` to a human-readable representation.
Fit_Error.to_display_text : Text
Fit_Error.to_display_text = "Could not fit the model: " + self.message.to_text
Fit_Error.to_display_text self = "Could not fit the model: " + self.message.to_text
## PRIVATE
Fit_Error.handle_java_exception =

View File

@ -18,7 +18,7 @@ type Statistic
## PRIVATE
Convert the Enso Statistic into Java equivalent.
to_moment_statistic : SingleValue
to_moment_statistic = case self of
to_moment_statistic self = case self of
Sum -> Moments.SUM
Mean -> Moments.MEAN
Variance p -> if p then Moments.VARIANCE_POPULATION else Moments.VARIANCE
@ -215,7 +215,7 @@ calculate_correlation_statistics_matrix data =
Arguments:
- statistic: Statistic to calculate.
Vector.Vector.compute : Statistic -> Any
Vector.Vector.compute statistic=Count =
Vector.Vector.compute self statistic=Count =
self.compute_bulk [statistic] . first
@ -224,7 +224,7 @@ Vector.Vector.compute statistic=Count =
Arguments:
- statistics: Set of statistics to calculate.
Vector.Vector.compute_bulk : [Statistic] -> [Any]
Vector.Vector.compute_bulk statistics=[Count, Sum] =
Vector.Vector.compute_bulk self statistics=[Count, Sum] =
compute_bulk self statistics

View File

@ -25,7 +25,7 @@ type Text
"Hello" + ", world!"
+ : Text -> Text
+ that = @Builtin_Method "Text.+"
+ self that = @Builtin_Method "Text.+"
## Checks whether `self` is equal to `that`.
@ -45,5 +45,5 @@ type Text
('é' == 'e\u0301') == True
== : Any -> Boolean
== that = if Meta.is_same_object self Text then Meta.is_same_object that Text else
== self that = if Meta.is_same_object self Text then Meta.is_same_object that Text else
Text_Utils.equals self that

View File

@ -27,7 +27,7 @@ type Encoding
## PRIVATE
Convert an Encoding to it's corresponding Java Charset
to_java_charset : Charset
to_java_charset =
to_java_charset self =
Panic.catch UnsupportedCharsetException (Charset.forName self.character_set) _->
Error.throw (Illegal_Argument_Error ("Unknown Character Set: " + self.character_set))
@ -99,4 +99,4 @@ type Encoding
type Encoding_Error (message:Text)
Encoding_Error.to_display_text : Text
Encoding_Error.to_display_text = "Encoding_Error: " + self.message
Encoding_Error.to_display_text self = "Encoding_Error: " + self.message

View File

@ -49,7 +49,7 @@ type Index_Out_Of_Bounds_Error index length
"건반(Korean)".length
Text.length : Integer
Text.length =
Text.length self =
iterator = BreakIterator.getCharacterInstance
iterator.setText self
@ -69,7 +69,7 @@ Text.length =
"Hello, world!".reverse
Text.reverse : Text
Text.reverse =
Text.reverse self =
reverseStringBuilder = StringBuilder.new self.length
iterator = BreakIterator.getCharacterInstance
iterator.setText self
@ -94,7 +94,7 @@ Text.reverse =
"aaa".each IO.println
Text.each : (Text -> Any) -> Nothing
Text.each function =
Text.each self function =
iterator = BreakIterator.getCharacterInstance
iterator.setText self
@ -123,7 +123,7 @@ Text.each function =
"건반(Korean)".at 1 == "반"
Text.at : Integer -> Text ! Index_Out_Of_Bounds_Error
Text.at index =
Text.at self index =
case index < 0 of
True ->
length = self.length
@ -152,7 +152,7 @@ Text.at index =
"건반(Korean)".characters
Text.characters : Vector.Vector Text
Text.characters =
Text.characters self =
bldr = Vector.new_builder
self.each bldr.append
bldr.to_vector
@ -215,7 +215,7 @@ Text.characters =
regex = ".+@.+"
"contact@enso.org".match regex
Text.match : Text | Engine.Pattern -> Mode.Mode -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Vector.Vector Option.Option -> Match | Vector.Vector Match | Nothing ! Regex.Compile_Error
Text.match pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothing dot_matches_newline=Nothing multiline=Nothing comments=Nothing extra_opts=[] =
Text.match self pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothing dot_matches_newline=Nothing multiline=Nothing comments=Nothing extra_opts=[] =
compiled_pattern = Regex.compile pattern match_ascii=match_ascii case_insensitive=case_insensitive dot_matches_newline=dot_matches_newline multiline=multiline comments=comments extra_opts=extra_opts
compiled_pattern.match self mode
@ -277,7 +277,7 @@ Text.match pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothing do
regex = ".+@.+"
"contact@enso.org".matches regex
Text.matches : Text | Engine.Pattern -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Vector.Vector Option.Option -> Boolean ! Regex.Compile_Error
Text.matches pattern match_ascii=Nothing case_insensitive=Nothing dot_matches_newline=Nothing multiline=Nothing comments=Nothing extra_opts=[] =
Text.matches self pattern match_ascii=Nothing case_insensitive=Nothing dot_matches_newline=Nothing multiline=Nothing comments=Nothing extra_opts=[] =
compiled_pattern = Regex.compile pattern match_ascii=match_ascii case_insensitive=case_insensitive dot_matches_newline=dot_matches_newline multiline=multiline comments=comments extra_opts=extra_opts
compiled_pattern.matches self
@ -338,7 +338,7 @@ Text.matches pattern match_ascii=Nothing case_insensitive=Nothing dot_matches_ne
text = "Now I know my ABCs"
text.find "\w{1,3}"
Text.find : Text | Engine.Pattern -> Mode.Mode -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Boolean | Nothing -> Vector.Vector Option.Option -> Text | Vector.Vector Text | Nothing
Text.find pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothing dot_matches_newline=Nothing multiline=Nothing comments=Nothing extra_opts=[] =
Text.find self pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothing dot_matches_newline=Nothing multiline=Nothing comments=Nothing extra_opts=[] =
compiled_pattern = Regex.compile pattern match_ascii=match_ascii case_insensitive=case_insensitive dot_matches_newline=dot_matches_newline multiline=multiline comments=comments extra_opts=extra_opts
compiled_pattern.find self mode
@ -370,7 +370,7 @@ Text.find pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothing dot
'abc def\tghi'.split '\\s+' Regex_Matcher == ["abc", "def", "ghi"]
Text.split : Text -> (Text_Matcher | Regex_Matcher) -> Vector.Vector Text
Text.split delimiter="," matcher=Text_Matcher = if delimiter.is_empty then Error.throw (Illegal_Argument_Error "The delimiter cannot be empty.") else
Text.split self delimiter="," matcher=Text_Matcher = if delimiter.is_empty then Error.throw (Illegal_Argument_Error "The delimiter cannot be empty.") else
case matcher of
Text_Matcher case_sensitivity ->
delimiters = Vector.Vector <| case case_sensitivity of
@ -465,7 +465,7 @@ Text.split delimiter="," matcher=Text_Matcher = if delimiter.is_empty then Error
"aaa aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher . should_equal "ca aaa"
"aaa aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal "aaa ca"
Text.replace : Text -> Text -> (Matching_Mode.First | Matching_Mode.Last | Mode.All) -> (Text_Matcher | Regex_Matcher) -> Text
Text.replace term="" new_text="" mode=Mode.All matcher=Text_Matcher = if term.is_empty then self else
Text.replace self term="" new_text="" mode=Mode.All matcher=Text_Matcher = if term.is_empty then self else
case matcher of
Text_Matcher case_sensitivity ->
array_from_single_result result = case result of
@ -517,7 +517,7 @@ Text.replace term="" new_text="" mode=Mode.All matcher=Text_Matcher = if term.is
"แมวมีสี่ขา".words == ['แมว', 'มี', 'สี่', 'ขา']
Text.words : Boolean -> Vector.Vector Text
Text.words keep_whitespace=False =
Text.words self keep_whitespace=False =
iterator = BreakIterator.getWordInstance
iterator.setText self
bldr = Vector.new_builder
@ -560,7 +560,7 @@ Text.words keep_whitespace=False =
'\na\nb\n'.lines keep_endings=True == ['\n', 'a\n', 'b\n']
Text.lines : Boolean -> Vector.Vector Text
Text.lines keep_endings=False =
Text.lines self keep_endings=False =
Vector.Vector (Text_Utils.split_on_lines self keep_endings)
## Checks whether `self` is equal to `that`, ignoring the case of the texts.
@ -586,7 +586,7 @@ Text.lines keep_endings=False =
(('É' . equals_ignore_case 'é') && ('é' . equals_ignore_case 'e\u0301')) == True
Text.equals_ignore_case : Text -> Locale -> Boolean
Text.equals_ignore_case that locale=Locale.default =
Text.equals_ignore_case self that locale=Locale.default =
Text_Utils.equals_ignore_case self that locale.java_locale
## ADVANCED
@ -595,7 +595,7 @@ Text.equals_ignore_case that locale=Locale.default =
Unifies the case of all letters in the text, generating a key which can be
used to perform case-insensitive comparisons.
Text.to_case_insensitive_key : Locale -> Text
Text.to_case_insensitive_key locale=Locale.default =
Text.to_case_insensitive_key self locale=Locale.default =
Text_Utils.case_insensitive_key self locale.java_locale
## Compare two texts to discover their ordering.
@ -608,7 +608,7 @@ Text.to_case_insensitive_key locale=Locale.default =
"a".compare_to "b"
Text.compare_to : Text -> Ordering
Text.compare_to that =
Text.compare_to self that =
comparison_result = Text_Utils.compare_normalized self that
if comparison_result == 0 then Ordering.Equal else
if comparison_result < 0 then Ordering.Less else
@ -624,7 +624,7 @@ Text.compare_to that =
"a".compare_to_ignore_case "b"
Text.compare_to_ignore_case : Text -> Locale -> Ordering
Text.compare_to_ignore_case that locale=Locale.default =
Text.compare_to_ignore_case self that locale=Locale.default =
comparison_result = Text_Utils.compare_normalized_ignoring_case self that locale.java_locale
if comparison_result == 0 then Ordering.Equal else
if comparison_result < 0 then Ordering.Less else
@ -642,7 +642,7 @@ Text.compare_to_ignore_case that locale=Locale.default =
"aaa".is_empty
Text.is_empty : Boolean
Text.is_empty = self == ""
Text.is_empty self = self == ""
## ALIAS Check Non-Emptiness
@ -656,7 +656,7 @@ Text.is_empty = self == ""
"aaa".not_empty
Text.not_empty : Boolean
Text.not_empty = self.is_empty.not
Text.not_empty self = self.is_empty.not
## Inserts text value at the specified index.
@ -680,7 +680,7 @@ Text.not_empty = self.is_empty.not
"Hello World!".insert 5 " Cruel" == "Hello Cruel World!"
"Hello World!".insert -1 " Cruel" == "Hello World! Cruel"
Text.insert : Integer -> Text -> Text ! Index_Out_Of_Bounds_Error
Text.insert index that =
Text.insert self index that =
len = self.length
idx = if index < 0 then len + index + 1 else index
if (idx < 0) || (idx > len) then Error.throw (Index_Out_Of_Bounds_Error index len) else
@ -712,7 +712,7 @@ Text.insert index that =
"A0".is_digit 1 == True
"건반(Korean)".is_digit 1 == False
Text.is_digit : Integer -> Boolean ! Index_Out_Of_Bounds_Error
Text.is_digit (index=0) =
Text.is_digit self (index=0) =
grapheme = self.at index
char = (Text_Utils.get_chars grapheme).at 0
char>=48 && char<=57
@ -725,7 +725,7 @@ Text.is_digit (index=0) =
' \t'.is_whitespace == True
"0 ".is_whitespace == False
Text.is_whitespace : Boolean
Text.is_whitespace =
Text.is_whitespace self =
Text_Utils.is_all_whitespace self
## Returns a vector containing bytes representing the specified encoding of the
@ -746,7 +746,7 @@ Text.is_whitespace =
"Hello".bytes (Encoding.ascii)
Text.bytes : Encoding -> Problem_Behavior -> Vector.Vector Byte
Text.bytes encoding on_problems=Report_Warning =
Text.bytes self encoding on_problems=Report_Warning =
result = Encoding_Utils.get_bytes self (encoding . to_java_charset)
vector = Vector.Vector result.result
if result.warnings.is_nothing then vector else
@ -792,7 +792,7 @@ Text.from_bytes bytes encoding on_problems=Report_Warning =
"Hello".utf_8
Text.utf_8 : Problem_Behavior -> Vector.Vector Byte
Text.utf_8 on_problems=Report_Warning =
Text.utf_8 self on_problems=Report_Warning =
self.bytes Encoding.utf_8 on_problems
## Takes a vector of bytes and returns Text resulting from decoding it as UTF-8.
@ -826,7 +826,7 @@ Text.from_utf_8 bytes on_problems=Report_Warning =
"Hello".char_vector
Text.char_vector : Vector.Vector Integer
Text.char_vector = Vector.Vector (Text_Utils.get_chars self)
Text.char_vector self = Vector.Vector (Text_Utils.get_chars self)
## Takes a vector of characters and returns the text that results from it.
@ -849,7 +849,7 @@ Text.from_char_vector chars = Text_Utils.from_chars chars.to_array
"Hello".codepoints
Text.codepoints : Vector.Vector Integer
Text.codepoints = Vector.Vector (Text_Utils.get_codepoints self)
Text.codepoints self = Vector.Vector (Text_Utils.get_codepoints self)
## Takes an array of numbers and returns the text resulting from interpreting it
as a sequence of Unicode codepoints.
@ -902,7 +902,7 @@ Text.from_codepoints codepoints = Text_Utils.from_codepoints codepoints.to_array
"Hello!".starts_with "[a-z]" Regex_Matcher == False
"Hello!".starts_with "[A-Z]" Regex_Matcher == True
Text.starts_with : Text -> Matcher -> Boolean
Text.starts_with prefix matcher=Text_Matcher = case matcher of
Text.starts_with self prefix matcher=Text_Matcher = case matcher of
Text_Matcher case_sensitivity -> case case_sensitivity of
True ->
self.take (Text_Sub_Range.First prefix.length) == prefix
@ -939,7 +939,7 @@ Text.starts_with prefix matcher=Text_Matcher = case matcher of
"Hello World".ends_with "world" (Text_Matcher Case_Insensitive) == True
"Hello World".ends_with "[A-Z][a-z]{4}" Regex_Matcher == True
Text.ends_with : Text -> Matcher -> Boolean
Text.ends_with suffix matcher=Text_Matcher = case matcher of
Text.ends_with self suffix matcher=Text_Matcher = case matcher of
Text_Matcher case_sensitivity -> case case_sensitivity of
True ->
self.take (Text_Sub_Range.Last suffix.length) == suffix
@ -1003,7 +1003,7 @@ Text.ends_with suffix matcher=Text_Matcher = case matcher of
"Hello!".contains "[a-z]" Regex_Matcher
Text.contains : Text -> Matcher -> Boolean
Text.contains term="" matcher=Text_Matcher = case matcher of
Text.contains self term="" matcher=Text_Matcher = case matcher of
Text_Matcher case_sensitivity -> case case_sensitivity of
True -> Text_Utils.contains self term
Case_Insensitive locale ->
@ -1020,7 +1020,7 @@ Text.contains term="" matcher=Text_Matcher = case matcher of
"cześć".to_json
Text.to_json : Json.String
Text.to_json = Json.String self
Text.to_json self = Json.String self
## Takes an integer and returns a new text, consisting of `count` concatenated
@ -1040,7 +1040,7 @@ Text.to_json = Json.String self
"Hello " * 2 == "Hello Hello "
Text.* : Integer -> Text
Text.* count = self.repeat count
Text.* self count = self.repeat count
## Takes an integer and returns a new text, consisting of `count` concatenated
copies of `self`.
@ -1059,7 +1059,7 @@ Text.* count = self.repeat count
"Hello ".repeat 2 == "Hello Hello "
Text.repeat : Integer -> Text
Text.repeat count=1 =
Text.repeat self count=1 =
## TODO max is a workaround until Range is sorted to make 0..-1 not cause an infinite loop
https://www.pivotaltracker.com/story/show/181435598
0.up_to (count.max 0) . fold "" acc-> _-> acc + self
@ -1098,7 +1098,7 @@ Text.repeat count=1 =
"Hello World!".take (Range 5 12) == " World!"
"Hello World!".take (Range 12 12) == ""
Text.take : (Text_Sub_Range | Range) -> Text ! Index_Out_Of_Bounds_Error
Text.take range =
Text.take self range =
char_range = case range of
Range _ _ _ -> Span_Module.range_to_char_indices self range
_ -> range.to_char_range self
@ -1138,7 +1138,7 @@ Text.take range =
"Hello World!".drop (Range 5 12) == "Hello"
"Hello World!".drop (Range 12 12) == "Hello World!"
Text.drop : (Text_Sub_Range | Range) -> Text ! Index_Out_Of_Bounds_Error
Text.drop range =
Text.drop self range =
char_range = case range of
Range _ _ _ -> Span_Module.range_to_char_indices self range
_ -> range.to_char_range self
@ -1179,7 +1179,7 @@ Text.drop range =
example_case_with_locale = "i".to_case Upper (Locale.new "tr") == "İ"
Text.to_case : Case -> Locale -> Text
Text.to_case case_option=Case.Lower locale=Locale.default = case case_option of
Text.to_case self case_option=Case.Lower locale=Locale.default = case case_option of
Case.Lower -> UCharacter.toLowerCase locale.java_locale self
Case.Upper -> UCharacter.toUpperCase locale.java_locale self
Case.Title -> UCharacter.toTitleCase locale.java_locale self Nothing
@ -1209,7 +1209,7 @@ Text.to_case case_option=Case.Lower locale=Locale.default = case case_option of
"HELLO".pad 8 "AB" Start == "BABHELLO"
Text.pad : Integer -> Text -> (Location.Start | Location.End) -> Text
Text.pad length=0 with_pad=' ' at=Location.End =
Text.pad self length=0 with_pad=' ' at=Location.End =
with_pad_length = with_pad.length
if with_pad_length == 0 then Error.throw (Illegal_Argument_Error "`with_pad` must not be an empty string.") else
pad_size = length - self.length
@ -1246,7 +1246,7 @@ Text.pad length=0 with_pad=' ' at=Location.End =
"ABC123".trim Start "ABC" == "123"
"ABBA123".trim Start "ABC" == "123"
Text.trim : (Location.Start | Location.End | Location.Both) -> (Text | (Text -> Boolean)) -> Text
Text.trim where=Location.Both what=_.is_whitespace =
Text.trim self where=Location.Both what=_.is_whitespace =
predicate = case what of
Text -> what.contains _
_ -> what
@ -1369,7 +1369,7 @@ Text.trim where=Location.Both what=_.is_whitespace =
"aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Text_Matcher == Span (Range 5 7) "aaa aaa"
"aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Regex_Matcher == Span (Range 4 6) "aaa aaa"
Text.location_of : Text -> (Matching_Mode.First | Matching_Mode.Last) -> Matcher -> Span | Nothing
Text.location_of term="" mode=Matching_Mode.First matcher=Text_Matcher = case matcher of
Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher = case matcher of
Text_Matcher case_sensitive -> case case_sensitive of
True ->
codepoint_span = case mode of
@ -1472,7 +1472,7 @@ Text.location_of term="" mode=Matching_Mode.First matcher=Text_Matcher = case ma
match_2 = ligatures . location_of_all "ffiff" matcher=(Text_Matcher Case_Insensitive)
match_2 . map .length == [2, 5]
Text.location_of_all : Text -> Matcher -> [Span]
Text.location_of_all term="" matcher=Text_Matcher = case matcher of
Text.location_of_all self term="" matcher=Text_Matcher = case matcher of
Text_Matcher case_sensitive -> if term.is_empty then Vector.new (self.length + 1) (ix -> Span (Range ix ix) self) else case case_sensitive of
True ->
codepoint_spans = Vector.Vector <| Text_Utils.span_of_all self term

View File

@ -15,7 +15,7 @@ type Line_Ending_Style
## Returns the text equivalent of the line ending.
to_text : Text
to_text = case self of
to_text self = case self of
Unix -> '\n'
Windows -> '\r\n'
Mac_Legacy -> '\r'

View File

@ -10,7 +10,7 @@ from Standard.Base.Error.Common import Wrapped_Dataflow_Error
type No_Matches_Found (criteria : Vector Text)
No_Matches_Found.to_display_text : Text
No_Matches_Found.to_display_text =
No_Matches_Found.to_display_text self =
"The criteria "+self.criteria.to_text+" did not match any names in the input."
@ -58,7 +58,7 @@ type Regex_Matcher (case_sensitive : (True | Case_Insensitive) = True) (multilin
Compiles a provided pattern according to the rules defined in this
`Regex_Matcher`.
Regex_Matcher.compile : Text -> Pattern
Regex_Matcher.compile pattern =
Regex_Matcher.compile self pattern =
case_insensitive = case self.case_sensitive of
True -> False
## TODO [RW] Currently locale is not supported in case-insensitive
@ -81,7 +81,7 @@ Regex_Matcher.compile pattern =
Text_Matcher.match_single_criterion "Foobar" "foo" == False
Text_Matcher.match_single_criterion : Text -> Text -> Boolean
Text_Matcher.match_single_criterion name criterion =
Text_Matcher.match_single_criterion self name criterion =
case self.case_sensitive of
True -> name == criterion
Case_Insensitive locale -> name.equals_ignore_case criterion locale=locale
@ -100,7 +100,7 @@ Text_Matcher.match_single_criterion name criterion =
Regex_Matcher case_sensitive=Case_Insensitive . match_single_criterion "Foobar" "f.*" == True
Regex_Matcher.match_single_criterion : Text -> Text -> Boolean
Regex_Matcher.match_single_criterion name criterion =
Regex_Matcher.match_single_criterion self name criterion =
self.compile criterion . matches name
## UNSTABLE
@ -142,7 +142,7 @@ Regex_Matcher.match_single_criterion name criterion =
Text_Matcher.match_criteria [Pair "foo" 42, Pair "bar" 33, Pair "baz" 10, Pair "foo" 0, Pair 10 10] ["bar", "foo"] reorder=True name_mapper=_.name == [Pair "bar" 33, Pair "foo" 42, Pair "foo" 0]
Text_Matcher.match_criteria : Vector Any -> Vector Text -> Boolean -> (Any -> Text) -> Problem_Behavior -> Vector Any ! No_Matches_Found
Text_Matcher.match_criteria = match_criteria_implementation self
Text_Matcher.match_criteria self = match_criteria_implementation self
## UNSTABLE
Selects objects from an input list that match any of the provided criteria.
@ -183,7 +183,7 @@ Text_Matcher.match_criteria = match_criteria_implementation self
Text_Matcher.match_criteria [Pair "foo" 42, Pair "bar" 33, Pair "baz" 10, Pair "foo" 0, Pair 10 10] ["bar", "foo"] reorder=True name_mapper=_.name == [Pair "bar" 33, Pair "foo" 42, Pair "foo" 0]
Regex_Matcher.match_criteria : Vector Any -> Vector Text -> Boolean -> (Any -> Text) -> Problem_Behavior -> Vector Any ! No_Matches_Found
Regex_Matcher.match_criteria = match_criteria_implementation self
Regex_Matcher.match_criteria self = match_criteria_implementation self
## A common supertype representing a matching strategy.
type Matcher
@ -212,17 +212,17 @@ type Match_Matrix
# Checks if the ith object is matched by any criterion.
is_object_matched_by_anything : Integer -> Boolean
is_object_matched_by_anything i =
is_object_matched_by_anything self i =
self.matrix.at i . any x->x
# Checks if the ith criterion matches any objects.
does_criterion_match_anything : Integer -> Boolean
does_criterion_match_anything i =
does_criterion_match_anything self i =
self.matrix.map (col -> col.at i) . any x->x
## PRIVATE
Extracts the list of criteria that did not have any matches.
unmatched_criteria =
unmatched_criteria self =
checked_criteria = self.criteria.map_with_index j-> criterion->
has_matches = self.does_criterion_match_anything j
Pair has_matches criterion
@ -231,14 +231,14 @@ type Match_Matrix
## PRIVATE
Returns the list of criteria that match the ith object.
criteria_matching_object : Integer -> Vector
criteria_matching_object i =
criteria_matching_object self i =
self.criteria.filter_with_index j-> _->
self.matrix . at i . at j
## PRIVATE
Returns the list of criteria indices that match the ith object.
criteria_indices_matching_object : Integer -> Vector
criteria_indices_matching_object i =
criteria_indices_matching_object self i =
(0.up_to self.criteria.length).filter j->
self.matrix . at i . at j

View File

@ -4,4 +4,4 @@
Forces flattening of a text value.
optimize : Text
optimize = @Builtin_Method "Prim_Text_Helper.optimize"
optimize text = @Builtin_Method "Prim_Text_Helper.optimize"

View File

@ -128,6 +128,6 @@ type No_Such_Group_Error (id : Text | Integer)
Provides a human-readable representation of the `No_Such_Group_Error`.
No_Such_Group_Error.to_display_text : Text
No_Such_Group_Error.to_display_text = case self.id of
No_Such_Group_Error.to_display_text self = case self.id of
Integer -> "No group exists with the index " + self.id.to_text + "."
Text -> "No group exists with the name " + self.id + "."

View File

@ -42,7 +42,7 @@ type Engine
- options: The options to configure the matching process with. These are
merged with the specific `engine_opts`.
compile : Text -> Vector Global_Option.Option -> Pattern ! (Regex.Compile_Error | Invalid_Option_Error)
compile _ _ = Errors.unimplemented "This is an interface only."
compile self _ _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -52,7 +52,7 @@ type Engine
Arguments:
- expression: The expression to escape metacharacters in.
escape : Text -> Text
escape _ = Errors.unimplemented "This is an interface only."
escape self _ = Errors.unimplemented "This is an interface only."
## The `Data.Text.Regex.Engine.Pattern` interface.
type Pattern
@ -80,7 +80,7 @@ type Pattern
mode that permits multiple matches, it will always return a `Vector`,
even if only a single match is found.
match : Text -> Mode.Mode -> Match | Vector.Vector Match | Nothing
match _ _ = Errors.unimplemented "This is an interface only."
match self _ _ _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -90,7 +90,7 @@ type Pattern
Arguments:
- input: The text to check for matching.
matches : Text -> Boolean
matches _ = Errors.unimplemented "This is an interface only."
matches self _ _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -110,7 +110,7 @@ type Pattern
mode that permits multiple matches, it will always return a `Vector`,
even if only a single match is found.
find : Text -> Mode.Mode -> Text | Vector.Vector Text | Nothing
find _ _ = Errors.unimplemented "This is an interface only."
find self _ _ _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -123,7 +123,7 @@ type Pattern
This method will _always_ return a vector. If no splits take place, the
vector will contain a single element.
split : Text -> (Mode.First | Integer | Mode.All) -> Vector.Vector Text
split _ _ = Errors.unimplemented "This is an interface only."
split self _ _ _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -139,7 +139,7 @@ type Pattern
If this method performs no replacements it will return the `input` text
unchanged.
replace : Text -> Text -> (Mode.First | Integer | Mode.All | Mode.Full) -> Text
replace _ _ _ = Errors.unimplemented "This is an interface only."
replace self _ _ _ _ = Errors.unimplemented "This is an interface only."
## The `Data.Text.Regex.Engine.Match` interface.
type Match
@ -167,7 +167,7 @@ type Match
If the regex contained named groups, these may also be accessed by
index based on their position in the pattern.
group : Integer | Text -> Text | Nothing ! Regex.No_Such_Group_Error
group _ = Errors.unimplemented "This is an interface only."
group self _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -187,7 +187,7 @@ type Match
If the regex contained named groups, these may also be accessed by
index based on their position in the pattern.
groups : (a : Any) -> Vector.Vector (Text | a)
groups _ = Errors.unimplemented "This is an interface only."
groups self _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -200,7 +200,7 @@ type Match
index did not participate in the match. This should default to
`Nothing`.
named_groups : (a : Any) -> Map Text (Text | a)
named_groups _ = Errors.unimplemented "This is an interface only."
named_groups self _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -211,7 +211,7 @@ type Match
Arguments:
- id: The identifier for the group to fetch the start index for.
start : Integer | Text -> Integer | Nothing ! Regex.No_Such_Group_Error
start _ = Errors.unimplemented "This is an interface only."
start self _ = Errors.unimplemented "This is an interface only."
## PRIVATE
@ -222,7 +222,7 @@ type Match
Arguments:
- id: The identifier for the group to fetch the end index for.
end : Integer | Text -> Integer | Nothing ! Regex.No_Such_Group_Error
end _ = Errors.unimplemented "This is an intercace only."
end self _ = Errors.unimplemented "This is an intercace only."
## PRIVATE
@ -232,15 +232,15 @@ type Match
Arguments:
- id: The identifier for the group to fetch the end index for.
span : Integer | Text -> Span | Nothing ! Regex.No_Such_Group_Error
span _ = Errors.unimplemented "This is an interface only."
span self _ = Errors.unimplemented "This is an interface only."
## PRIVATE
Returns the start character index of the match's region.
start_position : Integer
start_position = Errors.unimplemented "This is an interface only."
start_position self = Errors.unimplemented "This is an interface only."
## Returns the end character index of the match's region.
end_position : Integer
end_position = Errors.unimplemented "This is an interface only."
end_position self = Errors.unimplemented "This is an interface only."

View File

@ -112,7 +112,7 @@ type Engine
engine = Default_Engine.new
engine.compile expression options
compile : Text -> Vector Global_Option.Option -> Pattern ! (Regex.Compile_Error | Invalid_Option_Error)
compile expression options =
compile self expression options =
all_options = options + self.engine_opts
options_bitmask = from_enso_options all_options
unicode_regex = UnicodeRegex.new
@ -147,7 +147,7 @@ type Engine
engine = Default_Engine.new
engine.escape literal_string
escape : Text -> Text
escape expression = Java_Pattern.quote expression
escape self expression = Java_Pattern.quote expression
## The default implementation of the `Data.Text.Regex.Engine.Pattern` interface.
type Pattern
@ -179,7 +179,7 @@ type Pattern
will not contain "s". To get consistent behavior that does not depend
on the encoding, we normalize all input.
build_matcher : Text -> Integer -> Integer -> Java_Matcher
build_matcher input start end =
build_matcher self input start end =
## TODO [RW] Normalization had to be disabled - since start and end are
in code unit space, normalization could shift these indices!
This should be addressed when reviewing
@ -258,7 +258,7 @@ type Pattern
input = "abcdefghij"
pattern.match input mode=Mode.Full
match : Text -> Mode.Mode -> Match | Vector.Vector Match | Nothing
match input mode=Mode.All =
match self input mode=Mode.All =
do_match_mode mode start end = case mode of
Mode.First ->
internal_matcher = self.build_matcher input start end
@ -341,7 +341,7 @@ type Pattern
input = "aa"
pattern.matches input
matches : Text -> Boolean
matches input = case self.match input mode=Mode.Full of
matches self input = case self.match input mode=Mode.Full of
Match _ _ _ _ -> True
Vector.Vector _ -> True
_ -> False
@ -410,7 +410,7 @@ type Pattern
input = "abcdefghij"
pattern.find input mode=Mode.Full
find : Text -> Mode.Mode -> Text | Vector.Vector Text | Nothing
find input mode=Mode.All =
find self input mode=Mode.All =
matches = self.match input mode
case matches of
Match _ _ _ _ -> matches.group 0
@ -462,7 +462,7 @@ type Pattern
input = "bacadaeaf"
pattern.match input
split : Text -> (Mode.First | Integer | Mode.All) -> Vector.Vector Text
split input mode=Mode.All =
split self input mode=Mode.All =
# Java uses this to mean the max length of the resulting array, so we
# add 1.
limit = case mode of
@ -531,7 +531,7 @@ type Pattern
input = "aabbaabbbbbaab"
pattern.replace input "REPLACED"
replace : Text -> Text -> (Mode.First | Integer | Mode.All | Mode.Full | Matching_Mode.Last) -> Text
replace input replacement mode=Mode.All =
replace self input replacement mode=Mode.All =
do_replace_mode mode start end = case mode of
Mode.First ->
internal_matcher = self.build_matcher input start end
@ -631,7 +631,7 @@ type Match
match = Examples.match
match.group "letters"
group : Integer | Text -> Text | Nothing ! Regex.No_Such_Group_Error
group id =
group self id =
Panic.recover Any (self.internal_match.group id) . map_error (handle_error _ id)
## Gets a vector containing the results of _all_ of the capturing groups in
@ -659,7 +659,7 @@ type Match
match = Examples.match
match.groups default="UNMATCHED"
groups : (a : Any) -> Vector.Vector (Text | a)
groups default=Nothing =
groups self default=Nothing =
group_numbers = 0.up_to self.internal_match.groupCount+1
group_numbers.map n->
case self.group n of
@ -684,7 +684,7 @@ type Match
match = Examples.match
matcg.named_groups default="UNMATCHED"
named_groups : (a : Any) -> Map Text (Text | a)
named_groups default=Nothing =
named_groups self default=Nothing =
group_names = Vector.Vector <|
Regex_Utils.get_group_names self.internal_match.pattern
pairs = group_names.map name->
@ -717,7 +717,7 @@ type Match
match = Examples.match
match.start 0
start : Integer | Text -> Integer | Nothing ! Regex.No_Such_Group_Error
start id =
start self id =
result = Panic.recover Any (self.internal_match.start id)
no_errors = result.map_error (handle_error _ id)
if no_errors == -1 then Nothing else no_errors
@ -745,7 +745,7 @@ type Match
match = Examples.match
match.end 0
end : Integer | Text -> Integer | Nothing ! Regex.No_Such_Group_Error
end id =
end self id =
result = Panic.recover Any (self.internal_match.end id)
no_errors = result.map_error (handle_error _ id)
if no_errors == -1 then Nothing else no_errors
@ -771,7 +771,7 @@ type Match
match = Examples.match
match.span 0
span : Integer | Text -> Utf_16_Span | Nothing ! Regex.No_Such_Group_Error
span id = case self.group id of
span self id = case self.group id of
Nothing -> Nothing
_ -> Utf_16_Span (Range (self.start id) (self.end id)) self.input
@ -792,7 +792,7 @@ type Match
match = Examples.match
match.start_position
start_position : Integer
start_position = self.region_start
start_position self = self.region_start
## Returns the end character index of the match's region.
@ -811,7 +811,7 @@ type Match
match = Examples.match
match.end_position
end_position : Integer
end_position = self.region_end
end_position self = self.region_end
## PRIVATE
@ -912,7 +912,7 @@ type Mode_Error (message : Text)
Provides a human-readable representation of the invalid bounds error.
Mode_Error.to_display_text : Text
Mode_Error.to_display_text = self.message.to_text
Mode_Error.to_display_text self = self.message.to_text
## PRIVATE
@ -926,6 +926,6 @@ type Invalid_Option_Error (opt : Any)
Provides a human-readable representation of the invalid option error.
Invalid_Option_Error.to_display_text : Text
Invalid_Option_Error.to_display_text =
Invalid_Option_Error.to_display_text self =
"The option " + self.opt.to_text + " is not valid for the default regex engine."

View File

@ -47,7 +47,7 @@ type Span
Standard Annex 29. This is the smallest unit that still has semantic
meaning in most text-processing applications.
start : Integer
start = self.range.start
start self = self.range.start
## The index of the first character after `start` that is _not_ included in
the span.
@ -57,7 +57,7 @@ type Span
Standard Annex 29. This is the smallest unit that still has semantic
meaning in most text-processing applications.
end : Integer
end = self.range.end
end self = self.range.end
## The length of the span in extended grapheme clusters.
@ -66,7 +66,7 @@ type Span
Standard Annex 29. This is the smallest unit that still has semantic
meaning in most text-processing applications.
length : Integer
length = self.range.length
length self = self.range.length
## Converts the span of extended grapheme clusters to a corresponding span
of UTF-16 code units.
@ -77,7 +77,7 @@ type Span
text = 'ae\u{301}fz'
(Span (Range 1 3) text).to_utf_16_span == (Utf_16_Span (Range 1 4) text)
to_utf_16_span : Utf_16_Span
to_utf_16_span =
to_utf_16_span self =
Utf_16_Span (range_to_char_indices self.text self.range) self.text
type Utf_16_Span
@ -100,16 +100,16 @@ type Utf_16_Span
## The index of the first code unit included in the span.
start : Integer
start = self.range.start
start self = self.range.start
## The index of the first code unit after `start` that is _not_ included in
the span.
end : Integer
end = self.range.end
end self = self.range.end
## The length of the span in UTF-16 code units.
length : Integer
length = self.range.length
length self = self.range.length
## Returns a span of extended grapheme clusters which is the closest
approximation of this span of code units.
@ -129,7 +129,7 @@ type Utf_16_Span
extended == Span (Range 0 3) text # The span is extended to the whole string since it contained code units from every grapheme cluster.
extended.to_utf_16_span == Utf_16_Span (Range 0 6) text
to_grapheme_span : Span
to_grapheme_span = if (self.start < 0) || (self.end > Text_Utils.char_length self.text) then Error.throw (Illegal_State_Error "Utf_16_Span indices are out of range of the associated text.") else
to_grapheme_span self = if (self.start < 0) || (self.end > Text_Utils.char_length self.text) then Error.throw (Illegal_State_Error "Utf_16_Span indices are out of range of the associated text.") else
if self.end < self.start then Error.throw (Illegal_State_Error "Utf_16_Span invariant violation: start <= end") else
case self.start == self.end of
True ->

View File

@ -40,7 +40,7 @@ type Text_Sub_Range
## PRIVATE
Finds code-point indices corresponding to the part of the input matching the `Text_Sub_Range`.
to_char_range : Text -> Range
to_char_range text =
to_char_range self text =
## Utility function to find char indices for Text_Sub_Range.
Arguments:

View File

@ -174,7 +174,7 @@ type Time
example_year = Time.now.year
year : Integer
year = self . internal_zoned_date_time . getYear
year self = self . internal_zoned_date_time . getYear
## Get the month portion of the time as a number from 1 to 12.
@ -185,7 +185,7 @@ type Time
example_month = Time.now.month
month : Integer
month = self . internal_zoned_date_time . getMonthValue
month self = self . internal_zoned_date_time . getMonthValue
## Get the day portion of the time.
@ -196,7 +196,7 @@ type Time
example_day = Time.now.day
day : Integer
day = self . internal_zoned_date_time . getDayOfMonth
day self = self . internal_zoned_date_time . getDayOfMonth
## Get the hour portion of the time.
@ -207,7 +207,7 @@ type Time
example_hour = Time.now.hour
hour : Integer
hour = self . internal_zoned_date_time . getHour
hour self = self . internal_zoned_date_time . getHour
## Get the minute portion of the time.
@ -218,7 +218,7 @@ type Time
example_minute = Time.now.minute
minute : Integer
minute = self . internal_zoned_date_time . getMinute
minute self = self . internal_zoned_date_time . getMinute
## Get the second portion of the time.
@ -229,7 +229,7 @@ type Time
example_second = Time.now.second
second : Integer
second = self . internal_zoned_date_time . getSecond
second self = self . internal_zoned_date_time . getSecond
## Get the nanosecond portion of the time.
@ -240,7 +240,7 @@ type Time
example_nanosecond = Time.now.nanosecond
nanosecond : Integer
nanosecond = self . internal_zoned_date_time . getNano
nanosecond self = self . internal_zoned_date_time . getNano
## Get the timezone for the time.
@ -251,7 +251,7 @@ type Time
example_zone = Time.now.zone
zone : Zone
zone = Zone.Zone self.internal_zoned_date_time.getZone
zone self = Zone.Zone self.internal_zoned_date_time.getZone
## Return the number of seconds from the Unix epoch.
@ -262,7 +262,7 @@ type Time
example_epoch = Time.now.to_epoch_seconds
to_epoch_seconds : Integer
to_epoch_seconds = self . internal_zoned_date_time . toEpochSecond
to_epoch_seconds self = self . internal_zoned_date_time . toEpochSecond
## Return the number of milliseconds from the Unix epoch.
@ -273,7 +273,7 @@ type Time
example_epoch = Time.now.to_epoch_milliseconds
to_epoch_milliseconds : Integer
to_epoch_milliseconds = self . internal_zoned_date_time . toInstant . toEpochMilli
to_epoch_milliseconds self = self . internal_zoned_date_time . toInstant . toEpochMilli
## Convert this point in time to time of day, discarding the time zone
information.
@ -285,7 +285,7 @@ type Time
example_time_of_day = Time.now.time_of_day
time_of_day : Time_Of_Day
time_of_day = Time_Of_Day.Time_Of_Day self.internal_zoned_date_time.toLocalTime
time_of_day self = Time_Of_Day.Time_Of_Day self.internal_zoned_date_time.toLocalTime
## ALIAS Time to Date
@ -299,7 +299,7 @@ type Time
example_date = Time.now.date
date : Date
date = self.internal_zoned_date_time.toLocalDate
date self = self.internal_zoned_date_time.toLocalDate
## ALIAS Change Time Zone
@ -316,7 +316,7 @@ type Time
exaomple_at_zone = Time.new 2020 . at_zone (Zone.new -4)
at_zone : Zone -> Time
at_zone zone = Time (self.internal_zoned_date_time . withZoneSameInstant zone.internal_zone_id)
at_zone self zone = Time (self.internal_zoned_date_time . withZoneSameInstant zone.internal_zone_id)
## Add the specified amount of time to this instant to produce a new instant.
@ -331,7 +331,7 @@ type Time
example_plus = Time.new 2020 + 15.years + 3.hours
+ : Duration -> Time
+ amount = Time (self . internal_zoned_date_time . plus amount.internal_period . plus amount.internal_duration)
+ self amount = Time (self . internal_zoned_date_time . plus amount.internal_period . plus amount.internal_duration)
## Subtract the specified amount of time from this instant to get a new
instant.
@ -347,7 +347,7 @@ type Time
example_minus = Time.new 2020 - 1.year - 9.months
- : Duration -> Time
- amount = Time (self . internal_zoned_date_time . minus amount.internal_period . minus amount.internal_duration)
- self amount = Time (self . internal_zoned_date_time . minus amount.internal_period . minus amount.internal_duration)
## Convert this time to text using the default formatter.
@ -358,7 +358,7 @@ type Time
example_to_text = Time.now.to_text
to_text : Text
to_text = Time_Utils.default_time_formatter . format self.internal_zoned_date_time
to_text self = Time_Utils.default_time_formatter . format self.internal_zoned_date_time
## Convert the time to JSON.
@ -369,7 +369,7 @@ type Time
example_to_json = Time.now.to_json
to_json : Json.Object
to_json = Json.from_pairs [["type", "Time"], ["year", self.year], ["month", self.month], ["day", self.day], ["hour", self.hour], ["minute", self.minute], ["second", self.second], ["nanosecond", self.nanosecond], ["zone", self.zone]]
to_json self = Json.from_pairs [["type", "Time"], ["year", self.year], ["month", self.month], ["day", self.day], ["hour", self.hour], ["minute", self.minute], ["second", self.second], ["nanosecond", self.nanosecond], ["zone", self.zone]]
## Format this time as text using the specified format specifier.
@ -448,7 +448,7 @@ type Time
example_format =
Time.parse "2020-10-08T16:41:13+03:00[Europe/Moscow]" . format "EEE MMM d (HH:mm)"
format : Text -> Text
format pattern =
format self pattern =
DateTimeFormatter.ofPattern pattern . format self.internal_zoned_date_time
## Compares `self` to `that` to produce an ordering.
@ -461,13 +461,13 @@ type Time
(Time.new 2000).compare_to (Time.new 2001)
compare_to : Time -> Ordering
compare_to that =
compare_to self that =
sign = self.internal_zoned_date_time.compareTo that.internal_zoned_date_time
Ordering.from_sign sign
## Compares two Time for equality.
== : Time -> Boolean
== that = case that of
== self that = case that of
Time _ -> self.internal_zoned_date_time.equals that.internal_zoned_date_time
_ -> False

View File

@ -136,6 +136,9 @@ type Date
## This type represents a date, often viewed as year-month-day.
Arguments:
- internal_local_date: The internal date representation.
For example, the value "2nd October 2007" can be stored in a `Date`.
This class does not store or represent a time or timezone. Instead, it
@ -154,7 +157,7 @@ type Date
example_year = Date.now.year
year : Integer
year = @Builtin_Method "Date.year"
year self = @Builtin_Method "Date.year"
## Get the month of year field, as a number from 1 to 12.
@ -163,7 +166,7 @@ type Date
example_month = Date.now.month
month : Integer
month = @Builtin_Method "Date.month"
month self = @Builtin_Method "Date.month"
## Get the day of month field.
@ -174,7 +177,7 @@ type Date
example_day = Date.now.day
day : Integer
day = @Builtin_Method "Date.day"
day self = @Builtin_Method "Date.day"
## Returns the number of week of year this date falls into.
@ -190,7 +193,7 @@ type Date
containing the first Thursday of the year. Therefore it is important to
properly specify the `locale` argument.
week_of_year : Locale.Locale -> Integer
week_of_year locale=Locale.default = Time_Utils.week_of_year self locale.java_locale
week_of_year self locale=Locale.default = Time_Utils.week_of_year self locale.java_locale
## ALIAS Date to Time
@ -208,7 +211,7 @@ type Date
example_to_time = Date.new 2020 2 3 . to_time Time_Of_Day.new Zone.utc
to_time : Time_Of_Day -> Zone -> Time
to_time time_of_day (zone = Zone.system) = Time.Time (Time_Utils.date_with_time self time_of_day.internal_local_time zone.internal_zone_id)
to_time self time_of_day (zone = Zone.system) = Time.Time (Time_Utils.date_with_time self time_of_day.internal_local_time zone.internal_zone_id)
## Add the specified amount of time to this instant to get another date.
@ -222,7 +225,7 @@ type Date
example_add = Date.new 2020 + 6.months
+ : Duration -> Date
+ amount = if amount.is_time then Error.throw (Time.Time_Error "Date does not support time intervals") else
+ self amount = if amount.is_time then Error.throw (Time.Time_Error "Date does not support time intervals") else
(Time_Utils.date_adjust self 1 amount.internal_period) . internal_local_date
## Subtract the specified amount of time from this instant to get another
@ -239,7 +242,7 @@ type Date
example_subtract = Date.new 2020 - 7.days
- : Duration -> Date
- amount = if amount.is_time then Error.throw (Time.Time_Error "Date does not support time intervals") else
- self amount = if amount.is_time then Error.throw (Time.Time_Error "Date does not support time intervals") else
(Time_Utils.date_adjust self -1 amount.internal_period) . internal_local_date
@ -250,7 +253,7 @@ type Date
example_to_json = Date.now.to_json
to_json : Json.Object
to_json = Json.from_pairs [["type", "Date"], ["day", self.day], ["month", self.month], ["year", self.year]]
to_json self = Json.from_pairs [["type", "Date"], ["day", self.day], ["month", self.month], ["year", self.year]]
## Format this date using the provided format specifier.
@ -288,7 +291,7 @@ type Date
example_format = Date.new 2020 6 2 . format "yyyyGG"
format : Text -> Text
format pattern = Time_Utils.local_date_format self pattern
format self pattern = Time_Utils.local_date_format self pattern
## Compares `self` to `that` to produce an ordering.
@ -300,12 +303,12 @@ type Date
(Date.new 2000).compare_to (Date.new 2001)
compare_to : Date -> Ordering
compare_to that =
compare_to self that =
sign = Time_Utils.compare_to self that
Ordering.from_sign sign
## Compares two Dates for equality.
== : Date -> Boolean
== that =
== self that =
sign = Time_Utils.compare_to self that
0 == sign

View File

@ -73,7 +73,7 @@ type Duration
example_add = 1.month + 12.hours
+ : Duration -> Duration
+ that =
+ self that =
period = self.internal_period . plus that.internal_period . normalized
duration = self.internal_duration . plus that.internal_duration
Duration period duration
@ -97,7 +97,7 @@ type Duration
example_subtract = 7.months - 30.minutes
- : Duration -> Duration
- that =
- self that =
period = self.internal_period . minus that.internal_period . normalized
duration = self.internal_duration . minus that.internal_duration
Duration period duration
@ -111,7 +111,7 @@ type Duration
example_nanos = Examples.duration.nanoseconds
nanoseconds : Integer
nanoseconds = self.internal_duration . toNanosPart
nanoseconds self = self.internal_duration . toNanosPart
## Get the portion of the duration expressed in milliseconds.
@ -122,7 +122,7 @@ type Duration
example_millis = Examples.duration.milliseconds
milliseconds : Integer
milliseconds = self.internal_duration . toMillisPart
milliseconds self = self.internal_duration . toMillisPart
## Get the portion of the duration expressed in seconds.
@ -133,7 +133,7 @@ type Duration
example_seconds = Examples.duration.milliseconds
seconds : Integer
seconds = self.internal_duration . toSecondsPart
seconds self = self.internal_duration . toSecondsPart
## Get the portion of the duration expressed in minutes.
@ -144,7 +144,7 @@ type Duration
example_minutes = Examples.duration.milliseconds
minutes : Integer
minutes = self.internal_duration . toMinutesPart
minutes self = self.internal_duration . toMinutesPart
## Get the portion of the duration expressed in hours.
@ -155,7 +155,7 @@ type Duration
example_hours = Examples.duration.milliseconds
hours : Integer
hours = self.internal_duration . toHours
hours self = self.internal_duration . toHours
## Get the portion of the duration expressed in days.
@ -166,7 +166,7 @@ type Duration
example_days = Examples.duration.milliseconds
days : Integer
days = self.internal_period . getDays
days self = self.internal_period . getDays
## Get the portion of the duration expressed in months.
@ -177,7 +177,7 @@ type Duration
example_months = Examples.duration.months
months : Integer
months = self.internal_period . getMonths
months self = self.internal_period . getMonths
## Get the portion of the duration expressed in years.
@ -188,7 +188,7 @@ type Duration
example_years = Examples.duration.years
years : Integer
years = self.internal_period . getYears
years self = self.internal_period . getYears
## Convert this duration to a Vector of years, months, days, hours, minutes,
seconds and nanosecnods.
@ -209,7 +209,7 @@ type Duration
example_to_vec = 800.nanoseconds . to_vector
to_vector : Vector.Vector Integer
to_vector = [self.years, self.months, self.days, self.hours, self.minutes, self.seconds, self.nanoseconds]
to_vector self = [self.years, self.months, self.days, self.hours, self.minutes, self.seconds, self.nanoseconds]
## A Duration to Json conversion.
@ -220,7 +220,7 @@ type Duration
example_to_json = 10.seconds.to_json
to_json : Json.Object
to_json =
to_json self =
b = Vector.new_builder
b.append ["type", "Duration"]
if self.years==0 . not then b.append ["years", self.years]
@ -241,7 +241,7 @@ type Duration
example_is_date = 10.seconds.is_date
is_date : Boolean
is_date = (self.years==0 . not) || (self.months==0 . not) || (self.days==0 . not)
is_date self = (self.years==0 . not) || (self.months==0 . not) || (self.days==0 . not)
## Check if this duration is time-based.
@ -252,7 +252,7 @@ type Duration
example_is_time = 10.seconds.is_time
is_time : Boolean
is_time = (self.hours==0 . not) || (self.minutes==0 . not) || (self.seconds==0 . not) || (self.nanoseconds==0 . not)
is_time self = (self.hours==0 . not) || (self.minutes==0 . not) || (self.seconds==0 . not) || (self.nanoseconds==0 . not)
## Check if this duration represents an empty time-span.
@ -263,7 +263,7 @@ type Duration
example_is_empty = 10.seconds.is_empty
is_empty : Boolean
is_empty = self.is_date.not && self.is_time.not
is_empty self = self.is_date.not && self.is_time.not
## Check two durations for equality.
@ -277,7 +277,7 @@ type Duration
example_eq = 60.seconds == 1.minute
== : Duration -> Boolean
== that = self.to_vector == that.to_vector
== self that = self.to_vector == that.to_vector
## Compares `self` to `that` to produce an ordering.
@ -294,7 +294,7 @@ type Duration
duration_2 = 12.months + 1.day
duration_1.compare_to duration_2
compare_to : Duration -> Ordering
compare_to that =
compare_to self that =
if self.years > that.years then Ordering.Greater else
if self.years < that.years then Ordering.Less else
if self.months > that.months then Ordering.Greater else
@ -313,7 +313,7 @@ type Duration
example_nano = 1.nanosecond
Integer.nanosecond : Duration
Integer.nanosecond = Duration (Java_Period.ofDays 0) (Java_Duration.ofNanos self)
Integer.nanosecond self = Duration (Java_Period.ofDays 0) (Java_Duration.ofNanos self)
## Create a duration of `self` nanoseconds.
@ -324,7 +324,7 @@ Integer.nanosecond = Duration (Java_Period.ofDays 0) (Java_Duration.ofNanos self
example_nano = 20.nanoseconds
Integer.nanoseconds : Duration
Integer.nanoseconds = self.nanosecond
Integer.nanoseconds self = self.nanosecond
## Create a duration of `self` milliseconds.
@ -335,7 +335,7 @@ Integer.nanoseconds = self.nanosecond
example_milli = 1.millisecond
Integer.millisecond : Duration
Integer.millisecond = Duration (Java_Period.ofDays 0) (Java_Duration.ofMillis self)
Integer.millisecond self = Duration (Java_Period.ofDays 0) (Java_Duration.ofMillis self)
## Create a duration of `self` milliseconds.
@ -346,7 +346,7 @@ Integer.millisecond = Duration (Java_Period.ofDays 0) (Java_Duration.ofMillis se
example_milli = 20.milliseconds
Integer.milliseconds : Duration
Integer.milliseconds = self.millisecond
Integer.milliseconds self = self.millisecond
## Create a duration of `self` seconds.
@ -357,7 +357,7 @@ Integer.milliseconds = self.millisecond
example_second = 1.second
Integer.second : Duration
Integer.second = Duration (Java_Period.ofDays 0) (Java_Duration.ofSeconds self)
Integer.second self = Duration (Java_Period.ofDays 0) (Java_Duration.ofSeconds self)
## Create a duration of `self` seconds.
@ -368,7 +368,7 @@ Integer.second = Duration (Java_Period.ofDays 0) (Java_Duration.ofSeconds self)
example_second = 20.seconds
Integer.seconds : Duration
Integer.seconds = self.second
Integer.seconds self = self.second
## Create a duration of `self` minutes.
@ -379,7 +379,7 @@ Integer.seconds = self.second
example_min = 1.minute
Integer.minute : Duration
Integer.minute = Duration (Java_Period.ofDays 0) (Java_Duration.ofMinutes self)
Integer.minute self = Duration (Java_Period.ofDays 0) (Java_Duration.ofMinutes self)
## Create a duration of `self` minutes.
@ -390,7 +390,7 @@ Integer.minute = Duration (Java_Period.ofDays 0) (Java_Duration.ofMinutes self)
example_min = 20.minutes
Integer.minutes : Duration
Integer.minutes = self.minute
Integer.minutes self = self.minute
## Create a duration of `self` hours.
@ -401,7 +401,7 @@ Integer.minutes = self.minute
example_hour = 1.hour
Integer.hour : Duration
Integer.hour = Duration (Java_Period.ofDays 0) (Java_Duration.ofHours self)
Integer.hour self = Duration (Java_Period.ofDays 0) (Java_Duration.ofHours self)
## Create a duration of `self` hours.
@ -412,7 +412,7 @@ Integer.hour = Duration (Java_Period.ofDays 0) (Java_Duration.ofHours self)
example_hour = 20.hours
Integer.hours : Duration
Integer.hours = self.hour
Integer.hours self = self.hour
## Create a duration of `self` days.
@ -423,7 +423,7 @@ Integer.hours = self.hour
example_day = 1.day
Integer.day : Duration
Integer.day = Duration (Java_Period.ofDays self . normalized) (Java_Duration.ofSeconds 0)
Integer.day self = Duration (Java_Period.ofDays self . normalized) (Java_Duration.ofSeconds 0)
## Create a duration of `self` days.
@ -434,7 +434,7 @@ Integer.day = Duration (Java_Period.ofDays self . normalized) (Java_Duration.ofS
example_day = 20.days
Integer.days : Duration
Integer.days = self.day
Integer.days self = self.day
## Create a duration of `self` months.
@ -445,7 +445,7 @@ Integer.days = self.day
example_month = 1.month
Integer.month : Duration
Integer.month = Duration (Java_Period.ofMonths self . normalized) (Java_Duration.ofSeconds 0)
Integer.month self = Duration (Java_Period.ofMonths self . normalized) (Java_Duration.ofSeconds 0)
## Create a duration of `self` months.
@ -456,7 +456,7 @@ Integer.month = Duration (Java_Period.ofMonths self . normalized) (Java_Duration
example_month = 6.months
Integer.months : Duration
Integer.months = self.month
Integer.months self = self.month
## Create a duration of `self` years.
@ -467,7 +467,7 @@ Integer.months = self.month
example_year = 1.year
Integer.year : Duration
Integer.year = Duration (Java_Period.ofYears self . normalized) (Java_Duration.ofSeconds 0)
Integer.year self = Duration (Java_Period.ofYears self . normalized) (Java_Duration.ofSeconds 0)
## Create a duration of `self` years.
@ -478,5 +478,5 @@ Integer.year = Duration (Java_Period.ofYears self . normalized) (Java_Duration.o
example_year = 20.years
Integer.years : Duration
Integer.years = self.year
Integer.years self = self.year

View File

@ -146,7 +146,7 @@ type Time_Of_Day
example_hour = Time_Of_Day.now.hour
hour : Integer
hour = self . internal_local_time . getHour
hour self = self . internal_local_time . getHour
## Get the minute portion of the time of day.
@ -157,7 +157,7 @@ type Time_Of_Day
example_minute = Time_Of_Day.now.minute
minute : Integer
minute = self . internal_local_time . getMinute
minute self = self . internal_local_time . getMinute
## Get the second portion of the time of day.
@ -168,7 +168,7 @@ type Time_Of_Day
example_second = Time_Of_Day.now.second
second : Integer
second = self . internal_local_time . getSecond
second self = self . internal_local_time . getSecond
## Get the nanosecond portion of the time of day.
@ -179,7 +179,7 @@ type Time_Of_Day
example_nanosecond = Time_Of_Day.now.nanosecond
nanosecond : Integer
nanosecond = self . internal_local_time . getNano
nanosecond self = self . internal_local_time . getNano
## Extracts the time as the number of seconds, from 0 to 24 * 60 * 60 - 1.
@ -190,7 +190,7 @@ type Time_Of_Day
example_to_seconds = Time_Of_Day.now.to_seconds
to_seconds : Integer
to_seconds = self . internal_local_time . toSecondOfDay
to_seconds self = self . internal_local_time . toSecondOfDay
## Combine this time of day with a date to create a point in time.
@ -205,7 +205,7 @@ type Time_Of_Day
example_to_time = Time_Of_Day.new 12 30 . to_time (Date.new 2020)
to_time : Date -> Zone -> Time
to_time date (zone = Zone.system) =
to_time self date (zone = Zone.system) =
Time.Time (self . internal_local_time . atDate date . atZone zone.internal_zone_id)
## Add the specified amount of time to this instant to get a new instant.
@ -220,7 +220,7 @@ type Time_Of_Day
example_plus = Time_Of_Day.new + 3.seconds
+ : Duration -> Time_Of_Day
+ amount = if amount.is_date then Error.throw (Time.Time_Error "Time_Of_Day does not support date intervals") else
+ self amount = if amount.is_date then Error.throw (Time.Time_Error "Time_Of_Day does not support date intervals") else
Time_Of_Day (self . internal_local_time . plus amount.internal_duration)
## Subtract the specified amount of time from this instant to get a new
@ -237,7 +237,7 @@ type Time_Of_Day
example_minus = Time_Of_Day.now - 12.hours
- : Duration -> Time_Of_Day
- amount = if amount.is_date then Error.throw (Time.Time_Error "Time_Of_Day does not support date intervals") else
- self amount = if amount.is_date then Error.throw (Time.Time_Error "Time_Of_Day does not support date intervals") else
Time_Of_Day (self . internal_local_time . minus amount.internal_duration)
## Format this time of day as text using the default formatter.
@ -249,7 +249,7 @@ type Time_Of_Day
example_to_text = Time_Of_Day.now.to_text
to_text : Text
to_text = Time_Utils.default_time_of_day_formatter . format self.internal_local_time
to_text self = Time_Utils.default_time_of_day_formatter . format self.internal_local_time
## A Time_Of_Day to Json conversion.
@ -260,7 +260,7 @@ type Time_Of_Day
example_to_json = Time_Of_Day.now.to_text
to_json : Json.Object
to_json = Json.from_pairs [["type", "Time_Of_Day"], ["hour", self.hour], ["minute", self.minute], ["second", self.second], ["nanosecond", self.nanosecond]]
to_json self = Json.from_pairs [["type", "Time_Of_Day"], ["hour", self.hour], ["minute", self.minute], ["second", self.second], ["nanosecond", self.nanosecond]]
## Format this time of day using the provided formatter pattern.
@ -309,7 +309,7 @@ type Time_Of_Day
example_format = Time_Of_Day.new 16 21 10 . format "'hour:'h"
format : Text -> Text
format pattern =
format self pattern =
DateTimeFormatter.ofPattern pattern . format self.internal_local_time
## Compares `self` to `that` to produce an ordering.
@ -327,12 +327,12 @@ type Time_Of_Day
time_2 = Time_Of_Day.new minute=50
time_1.compare_to time_2
compare_to : Time_Of_Day -> Ordering
compare_to that =
compare_to self that =
sign = self.internal_local_time.compareTo that.internal_local_time
Ordering.from_sign sign
## Compares two Time_Of_Day for equality.
== : Date -> Boolean
== that = case that of
== self that = case that of
Time_Of_Day _ -> self.internal_local_time.equals that.internal_local_time
_ -> False

View File

@ -120,7 +120,7 @@ type Zone
example_zone_id = Zone.system.zone_id
zone_id : Text
zone_id = self.internal_zone_id . getId
zone_id self = self.internal_zone_id . getId
## Convert the time zone to JSON.
@ -131,4 +131,4 @@ type Zone
example_to_json = Zone.system.to_json
to_json : Json.Object
to_json = Json.from_pairs [["type", "Zone"], ["id", self.zone_id]]
to_json self = Json.from_pairs [["type", "Zone"], ["id", self.zone_id]]

View File

@ -123,7 +123,7 @@ type Vector
[1, 2, 3, 4].length
length : Number
length = Polyglot.get_array_size self.to_array
length self = Polyglot.get_array_size self.to_array
## Gets an element from the vector at a specified index (0-based).
@ -142,7 +142,7 @@ type Vector
[1, 2, 3].at -1 == 3
at : Integer -> Any ! Index_Out_Of_Bounds_Error
at index =
at self index =
actual_index = if index < 0 then self.length + index else index
Panic.catch Invalid_Array_Index_Error (self.unsafe_at actual_index) _->
Error.throw (Index_Out_Of_Bounds_Error index self.length)
@ -155,7 +155,7 @@ type Vector
Thus it should only be used when the access is guaranteed to be within
bounds or with additional error handling.
unsafe_at : Integer -> Any
unsafe_at index =
unsafe_at self index =
self.to_array.at index
## Combines all the elements of the vector, by iteratively applying the
@ -175,7 +175,7 @@ type Vector
[0, 1, 2] . fold 0 (+)
fold : Any -> (Any -> Any -> Any) -> Any
fold init function =
fold self init function =
arr = self.to_array
f = acc -> ix -> function acc (arr.at ix)
0.up_to self.length . fold init f
@ -193,7 +193,7 @@ type Vector
[0, 1, 2] . fold 0 (s->i->e->s+i+e)
fold_with_index : Any -> (Any -> Integer -> Any -> Any) -> Any
fold_with_index init function =
fold_with_index self init function =
arr = self.to_array
f = acc -> ix -> function acc ix (arr.at ix)
0.up_to self.length . fold init f
@ -210,7 +210,7 @@ type Vector
[0, 1, 2] . reduce (+)
reduce : (Any -> Any -> Any) -> Any ! Empty_Error
reduce function =
reduce self function =
case self.not_empty of
True -> if self.length == 1 then self.unsafe_at 0 else
arr = self.to_array
@ -228,7 +228,7 @@ type Vector
[0, 1, 2].sum
sum : Any ! (Empty_Error | No_Such_Method_Error)
sum =
sum self =
result = Panic.recover Any <| self.reduce (+)
result.map_error x->case x of
No_Such_Method_Error _ _ -> x
@ -247,7 +247,7 @@ type Vector
[1, 2, 3, 4, 5].exists (> 3)
exists : (Any -> Boolean) -> Boolean
exists predicate =
exists self predicate =
0.up_to self.length . exists (idx -> (predicate (self.unsafe_at idx)))
## Returns the first element of the vector that satisfies the predicate or
@ -263,7 +263,7 @@ type Vector
[1, 2, 3, 4, 5].find (> 3)
find : (Any -> Boolean) -> Any ! Nothing
find predicate =
find self predicate =
len = self.length
go idx =
if (idx >= len) then Error.throw Nothing else
@ -284,7 +284,7 @@ type Vector
[1, 2, 3, 4, 5].any (> 3)
any : (Any -> Boolean) -> Boolean
any predicate = self.exists predicate
any self predicate = self.exists predicate
## Checks whether a predicate holds for all elements in this vector.
@ -298,7 +298,7 @@ type Vector
[-1, 1, 5, 8].all (< 0)
all : (Any -> Boolean) -> Boolean
all predicate = self . exists (predicate >> .not) . not
all self predicate = self . exists (predicate >> .not) . not
## Checks whether this vector contains a given value as an element.
@ -310,7 +310,7 @@ type Vector
[1, 383, 72, 301].contains 72
contains : Any -> Boolean
contains elem = self.exists ix-> ix == elem
contains self elem = self.exists ix-> ix == elem
## Checks if this vector is empty.
@ -319,7 +319,7 @@ type Vector
[].is_empty
is_empty : Boolean
is_empty = self.length == 0
is_empty self = self.length == 0
## Checks if this vector is not empty.
@ -328,7 +328,7 @@ type Vector
[1].not_empty
not_empty : Boolean
not_empty = self.is_empty.not
not_empty self = self.is_empty.not
## Selects all elements of this vector which satisfy a predicate.
@ -342,7 +342,7 @@ type Vector
[1, 2, 3, 4, 5].filter (> 3)
filter : (Any -> Boolean) -> Vector Any
filter predicate =
filter self predicate =
builder = self.fold new_builder builder-> elem->
if predicate elem then builder.append elem else builder
builder.to_vector
@ -359,7 +359,7 @@ type Vector
[0, 10, 2, 2].filter (==) == [0, 2]
filter_with_index : (Integer -> Any -> Boolean) -> Vector Any
filter_with_index predicate =
filter_with_index self predicate =
builder = self.fold_with_index new_builder builder-> ix-> elem->
if predicate ix elem then builder.append elem else builder
builder.to_vector
@ -383,7 +383,7 @@ type Vector
[1, 2, 3, 4, 5].partition (x -> x % 2 == 0) == (Pair [2, 4] [1, 3, 5])
partition : (Any -> Boolean) -> Pair (Vector Any) (Vector Any)
partition predicate =
partition self predicate =
pair = self.fold (Pair new_builder new_builder) acc-> elem->
case predicate elem of
True ->
@ -411,7 +411,7 @@ type Vector
["a", "b", "c", "d"].partition_with_index (ix -> _ -> ix % 2 == 0) == (Pair ["a", "c"] ["b", "d"])
partition_with_index : (Integer -> Any -> Boolean) -> Pair (Vector Any) (Vector Any)
partition_with_index predicate =
partition_with_index self predicate =
pair = self.fold_with_index (Pair new_builder new_builder) acc-> ix-> elem->
case predicate ix elem of
True -> Pair (acc.first.append elem) acc.second
@ -430,7 +430,7 @@ type Vector
[1, 2, 3] . map +1
map : (Any -> Any) -> Vector Any
map function =
map self function =
new self.length i-> function (self.unsafe_at i)
## Applies a function to each element of the vector, returning the vector
@ -445,7 +445,7 @@ type Vector
[0, 1, 2] . flat_map (n -> Vector.fill n n)
flat_map : (Any -> Vector Any) -> Vector Any
flat_map function =
flat_map self function =
self.map function . flatten
## Transforms a vector of vectors into a vector of inner elements - removes
@ -456,7 +456,7 @@ type Vector
[[1, 2, 3], [4, 10], [], [0], [0]] . flatten == [1, 2, 3, 4, 10, 0, 0]
flatten : Vector Any
flatten =
flatten self =
length = self.fold 0 acc-> elem-> acc + elem.length
arr = Array.new length
self.fold 0 i-> vec->
@ -479,7 +479,7 @@ type Vector
[1, 2, 3].map_with_index (+)
map_with_index : (Integer -> Any -> Any) -> Vector Any
map_with_index function = new self.length i-> function i (self.unsafe_at i)
map_with_index self function = new self.length i-> function i (self.unsafe_at i)
## Applies a function to each element of the vector.
@ -494,7 +494,7 @@ type Vector
[1, 2, 3, 4, 5] . each IO.println
each : (Any -> Any) -> Nothing
each f =
each self f =
0.up_to self.length . each ix->
f (self.unsafe_at ix)
@ -514,7 +514,7 @@ type Vector
[1, 2, 3, 4, 5] . each_with_index (ix->elem-> IO.println Pair ix elem)
each_with_index : (Integer -> Any -> Any) -> Nothing
each_with_index f =
each_with_index self f =
0.up_to self.length . each ix->
f ix (self.unsafe_at ix)
@ -526,7 +526,7 @@ type Vector
[1, 2].reverse
reverse : Vector Any
reverse = new self.length (i -> self.unsafe_at (self.length - (1 + i)))
reverse self = new self.length (i -> self.unsafe_at (self.length - (1 + i)))
## Generates a human-readable text representation of the vector.
@ -535,7 +535,7 @@ type Vector
[1, 2, 3].to_text == "[1, 2, 3]"
to_text : Text
to_text = self.map .to_text . join ", " "[" "]"
to_text self = self.map .to_text . join ", " "[" "]"
## UNSTABLE
Generates a human-readable text representation of the vector, keeping its
@ -551,7 +551,7 @@ type Vector
(0.up_to 100).to_vector.short_display_text max_entries=2 == "[0, 1 and 98 more elements]"
short_display_text : Integer -> Text
short_display_text max_entries=10 =
short_display_text self max_entries=10 =
if max_entries < 1 then Error.throw <| Illegal_Argument_Error "The `max_entries` parameter must be positive." else
prefix = self.take_start max_entries
if prefix.length == self.length then self.to_text else
@ -573,7 +573,7 @@ type Vector
[1, 2, 3] == [2, 3, 4]
== : Vector -> Boolean
== that =
== self that =
eq_at i = self.unsafe_at i == that.unsafe_at i
if self.length == that.length then 0.up_to self.length . all eq_at else False
@ -588,7 +588,7 @@ type Vector
[1] + [2]
+ : Vector Any -> Vector Any
+ that =
+ self that =
self_len = self.length
arr = Array.new (self_len + that.length)
Array.copy self.to_array 0 arr 0 self_len
@ -605,7 +605,7 @@ type Vector
[2, 3].prepend 1
prepend : Any -> Vector Any
prepend element = [element] + self
prepend self element = [element] + self
## Add `element` to the end of `self` vector.
@ -617,7 +617,7 @@ type Vector
[1, 2].append 3
append : Any -> Vector Any
append element = self + [element]
append self element = self + [element]
## When `self` is a vector of text values, concatenates all the values by
interspersing them with `separator`.
@ -632,7 +632,7 @@ type Vector
["foo", "bar", "baz"].join ", "
join : Text -> Text -> Text -> Text
join separator="" prefix="" suffix="" =
join self separator="" prefix="" suffix="" =
if self.is_empty then prefix+suffix else
if self.length == 1 then prefix + self.unsafe_at 0 + suffix else
prefix + self.unsafe_at 0 + (1.up_to self.length . fold "" acc-> i-> acc + separator + self.unsafe_at i) + suffix
@ -649,7 +649,7 @@ type Vector
[1, 2, 3, 4, 5, 6, 7, 8].slice 2 5 == [3, 4, 5]
take : Integer -> Integer -> Vector Any
take start end =
take self start end =
slice_start = Math.max 0 start
slice_end = Math.min self.length end
if slice_start >= slice_end then Vector (Array.new 0) else
@ -669,7 +669,7 @@ type Vector
[1, 2, 3, 4, 5].drop_start 1
drop_start : Integer -> Vector Any
drop_start count = self.take count self.length
drop_start self count = self.take count self.length
## Creates a new vector with elements at the beginning of the vector which
satisfy the provided predicate removed.
@ -684,7 +684,7 @@ type Vector
[1, 3, 5, 6, 8, 9, 10, 11, 13].drop_while (x-> x%2 == 1) == [6, 8, 9, 10, 11, 13]
drop_while : (Any -> Boolean) -> Vector Any
drop_while predicate =
drop_while self predicate =
find_first_false current =
if current >= self.length then Nothing else
case predicate (self.unsafe_at current) of
@ -704,7 +704,7 @@ type Vector
[1, 2, 3, 4, 5].drop_end 2
drop_end : Integer -> Vector Any
drop_end count = self.take 0 (self.length - count)
drop_end self count = self.take 0 (self.length - count)
## Creates a new vector, consisting of the first `count` elements on the
left of `self`.
@ -717,7 +717,7 @@ type Vector
[1, 2, 3, 4, 5].take_start 2
take_start : Integer -> Vector Any
take_start count = self.take 0 count
take_start self count = self.take 0 count
## Creates a new vector, consisting of the last `count` elements on the
right of `self`.
@ -730,7 +730,7 @@ type Vector
[1, 2, 3, 4, 5].take_end 3
take_end : Integer -> Vector Any
take_end count = self.take (self.length - count) self.length
take_end self count = self.take (self.length - count) self.length
## Performs a pair-wise operation passed in `function` on consecutive
elements of `self` and `that`.
@ -754,7 +754,7 @@ type Vector
[1, 2, 3].zip [4, 5, 6] == [[1, 4], [2, 5], [3, 6]]
zip : Vector Any -> (Any -> Any -> Any) -> Vector Any
zip that function=[_,_] =
zip self that function=[_,_] =
len = Math.min self.length that.length
new len i-> function (self.unsafe_at i) (that.unsafe_at i)
@ -778,7 +778,7 @@ type Vector
[1, 2, 3, 4, 5].pad 5 0
pad : Integer -> Any -> Vector Any
pad n elem =
pad self n elem =
if self.length >= n then self else
self + (fill n-self.length elem)
@ -789,7 +789,7 @@ type Vector
[1, 2, 3].to_json
to_json : Json.Array
to_json = Json.Array (self.map .to_json)
to_json self = Json.Array (self.map .to_json)
## Get the first element from the vector, or an `Empty_Error` if the vector
is empty.
@ -799,7 +799,7 @@ type Vector
[1, 2, 3, 4].head
head : Any ! Empty_Error
head = if self.length >= 1 then self.unsafe_at 0 else Error.throw Empty_Error
head self = if self.length >= 1 then self.unsafe_at 0 else Error.throw Empty_Error
## Get all elements in the vector except the first.
@ -808,7 +808,7 @@ type Vector
[1, 2, 3, 4].tail
tail : Vector ! Empty_Error
tail = if self.length >= 1 then self.drop_start 1 else
tail self = if self.length >= 1 then self.drop_start 1 else
Error.throw Empty_Error
## Get the all elements in the vector except the last.
@ -818,7 +818,7 @@ type Vector
[1, 2, 3, 4].init
init : Vector ! Empty_Error
init = if self.length >= 1 then self.drop_end 1 else Error.throw Empty_Error
init self = if self.length >= 1 then self.drop_end 1 else Error.throw Empty_Error
## Get the last element of the vector, or an `Empty_Error` if the vector is
empty.
@ -828,7 +828,7 @@ type Vector
[1, 2, 3, 4].last
last : Vector ! Empty_Error
last = if self.length >= 1 then self.unsafe_at (self.length-1) else
last self = if self.length >= 1 then self.unsafe_at (self.length-1) else
Error.throw Empty_Error
## Get the first element from the vector, or an `Empty_Error` if the vector
@ -839,7 +839,7 @@ type Vector
[1, 2, 3, 4].first
first : Vector ! Empty_Error
first = self.head
first self = self.head
## Get the second element from the vector, or a `Singleton_Error` if the
vector doesn't have a second element.
@ -851,7 +851,7 @@ type Vector
[1, 2, 3, 4].second
second : Vector ! Singleton_Error
second = if self.length >= 2 then self.unsafe_at 1 else
second self = if self.length >= 2 then self.unsafe_at 1 else
Error.throw (Singleton_Error self)
## Get all elements in the vector except the first.
@ -860,7 +860,7 @@ type Vector
The following code returns [2, 3, 4].
[1, 2, 3, 4].rest
rest : Vector ! Empty_Error
rest = self.tail
rest self = self.tail
## Sort the Vector.
@ -904,7 +904,7 @@ type Vector
[Pair 1 2, Pair -1 8].sort (_.first) (order = Sort_Direction.Descending)
sort : (Any -> Any) -> (Any -> Any -> Ordering) -> Sort_Direction -> Vector Any
sort (on = x -> x) (by = (_.compare_to _)) (order = Sort_Direction.Ascending) =
sort self (on = x -> x) (by = (_.compare_to _)) (order = Sort_Direction.Ascending) =
## Prepare the destination array that will underlie the vector. We do
not want to sort in place on the original vector, as `sort` is not
intended to be mutable.
@ -946,7 +946,7 @@ type Vector
[Pair 1 "a", Pair 2 "b", Pair 1 "c"] . distinct (on = _.first) == [Pair 1 "a", Pair 2 "b"]
distinct : (Any -> Any) -> Vector Any
distinct (on = x->x) =
distinct self (on = x->x) =
## TODO [JD] This is based on the Map class until a HashMap is available.
Current implementation allows for a consistent distinct with the Enso `==` operator.
@ -973,7 +973,7 @@ type Vector
Transform the vector into text for displaying as part of its default
visualization.
to_default_visualization_data : Text
to_default_visualization_data =
to_default_visualization_data self =
json = self.take_start 100 . to_json
json.to_text
@ -1030,15 +1030,15 @@ type Builder
Vector.new_builder.capacity
capacity : Integer
capacity = self.to_array.length
capacity self = self.to_array.length
## Checks if this builder is empty.
is_empty : Boolean
is_empty = self.length == 0
is_empty self = self.length == 0
## Checks if this builder is not empty.
not_empty : Boolean
not_empty = self.is_empty.not
not_empty self = self.is_empty.not
## Appends a new element into this builder and returns it, propagating any
errors that the provided element could have contained.
@ -1052,7 +1052,7 @@ type Builder
builder = Vector.new_builder
builder . append 10 . append 20
append : Any ! Error -> Builder ! Error
append item = case item of
append self item = case item of
_ ->
self.unsafe_append item
self
@ -1076,7 +1076,7 @@ type Builder
Vector.new_builder.unsafe_append 10
unsafe_append : Any -> Nothing
unsafe_append item = case self.capacity > self.length of
unsafe_append self item = case self.capacity > self.length of
True ->
self.to_array.set_at self.length item
Unsafe.set_atom_field self 1 (self.length + 1)
@ -1095,7 +1095,7 @@ type Builder
also allowed be negative, then the elements are indexed from the back
of the vector, i.e. -1 will correspond to the last element.
at : Integer -> Any ! Index_Out_Of_Bounds_Error
at index =
at self index =
actual_index = if index < 0 then self.length + index else index
Panic.catch Invalid_Array_Index_Error (self.to_array.at actual_index) _->
Error.throw (Index_Out_Of_Bounds_Error index self.length)
@ -1107,7 +1107,7 @@ type Builder
that says whether that value satisfies the conditions of the function.
exists : (Any -> Boolean) -> Boolean
exists predicate =
exists self predicate =
0.up_to self.length . exists (idx -> (predicate (self.to_array.at idx)))
## Converts this builder to a vector containing all the appended elements.
@ -1122,7 +1122,7 @@ type Builder
bldr.append 100
bldr.to_vector
to_vector : Vector Any
to_vector =
to_vector self =
old_array = self.to_array
new_array = Array.new self.length
Array.copy old_array 0 new_array 0 self.length
@ -1141,7 +1141,7 @@ type Index_Out_Of_Bounds_Error index length
Pretty prints an index out of bounds error.
Index_Out_Of_Bounds_Error.to_display_text : Text
Index_Out_Of_Bounds_Error.to_display_text =
Index_Out_Of_Bounds_Error.to_display_text self =
"The index " + self.index.to_text + " is out of bounds in a vector with length " + self.length.to_text + "."
## UNSTABLE
@ -1153,7 +1153,7 @@ type Empty_Error
Pretty prints the empty error.
Empty_Error.to_display_text : Text
Empty_Error.to_display_text = "The vector is empty."
Empty_Error.to_display_text self = "The vector is empty."
## UNSTABLE
@ -1167,7 +1167,7 @@ type Singleton_Error vec
Pretty prints the singleton error.
Singleton_Error.to_display_text : Text
Singleton_Error.to_display_text =
Singleton_Error.to_display_text self =
"The vector " + self.vec.to_text + " has only one element."
## PRIVATE

View File

@ -41,14 +41,14 @@ type Error
Arguments:
- handler: The function to call on this if it is an error value.
catch_primitive : (Error -> Any) -> Any
catch_primitive handler = @Builtin_Method "Error.catch_primitive"
catch_primitive self handler = @Builtin_Method "Error.catch_primitive"
## PRIVATE
UNSTABLE
Returns a textual representation of the stack trace attached to an error.
get_stack_trace_text : Text
get_stack_trace_text = @Builtin_Method "Error.get_stack_trace_text"
get_stack_trace_text self = @Builtin_Method "Error.get_stack_trace_text"
## Converts an error to a corresponding textual representation.
@ -57,13 +57,13 @@ type Error
Error.throw "foo" . to_text
to_text : Text
to_text = @Builtin_Method "Error.to_text"
to_text self = @Builtin_Method "Error.to_text"
## UNSTABLE
Returns a human-readable text representing this error.
to_display_text : Text
to_display_text = "Error: " + (self.catch Any .to_display_text)
to_display_text self = "Error: " + (self.catch Any .to_display_text)
## Executes the provided handler on an error, or returns the value unchanged.
@ -91,7 +91,7 @@ type Error
error = Error.throw 42
error.catch == 42
catch : Any -> (Error -> Any) -> Any
catch (error_type = Any) (handler = x->x) =
catch self (error_type = Any) (handler = x->x) =
self.catch_primitive error_value->
case error_value.is_a error_type of
True -> handler error_value
@ -108,7 +108,7 @@ type Error
example_display = Examples.throw_error.to_default_visualization_data
to_default_visualization_data : Text
to_default_visualization_data = self.catch Any .to_default_visualization_data
to_default_visualization_data self = self.catch Any .to_default_visualization_data
## UNSTABLE
@ -121,7 +121,7 @@ type Error
example_to_json = Examples.throw_error.to_json
to_json : Json.Object
to_json =
to_json self =
error_type = ["type", "Error"]
caught = self.catch
error_content = ["content", caught.to_json]
@ -145,7 +145,7 @@ type Error
map = Examples.map
map.get 10 . map_error (_ -> "The element 10 was not found.")
map_error : (Error -> Error) -> Any
map_error f = self.catch Any (x -> Error.throw (f x))
map_error self f = self.catch Any (x -> Error.throw (f x))
## ADVANCED
UNSTABLE
@ -155,7 +155,7 @@ type Error
The ordering of the resulting vector is such that the top stack frame is the
first element.
stack_trace : Vector.Vector Runtime.Stack_Trace_Element
stack_trace =
stack_trace self =
Panic.get_attached_stack_trace self
## Checks if `self` is an error.
@ -165,7 +165,7 @@ type Error
1.is_error
is_error : Boolean
is_error = True
is_error self = True
type Illegal_State_Error
@ -205,7 +205,7 @@ type Wrapped_Dataflow_Error payload
## PRIVATE
Throws the original error.
Wrapped_Dataflow_Error.unwrap = Error.throw self.payload
Wrapped_Dataflow_Error.unwrap self = Error.throw self.payload
type Caught_Panic
## A wrapper for a caught panic.
@ -222,11 +222,11 @@ type Caught_Panic
## Converts this caught panic into a dataflow error containing the same
payload and stack trace.
convert_to_dataflow_error : Error
convert_to_dataflow_error = @Builtin_Method "Caught_Panic.convert_to_dataflow_error"
convert_to_dataflow_error self = @Builtin_Method "Caught_Panic.convert_to_dataflow_error"
## Returns the stack trace of the caught panic.
stack_trace : Vector.Vector Runtime.Stack_Trace_Element
stack_trace =
stack_trace self =
Panic.get_attached_stack_trace self
## Panics.
@ -527,7 +527,7 @@ type No_Such_Method_Error target symbol
error = Examples.no_such_method
error.method_name
No_Such_Method_Error.method_name : Text
No_Such_Method_Error.method_name =
No_Such_Method_Error.method_name self =
Meta.meta self.symbol . name
@ -612,7 +612,7 @@ type Unimplemented_Error message
Converts the unimplemented error to a human-readable error message.
Unimplemented_Error.to_display_text : Text
Unimplemented_Error.to_display_text = "An implementation is missing: " + self.message
Unimplemented_Error.to_display_text self = "An implementation is missing: " + self.message
## ADVANCED

View File

@ -28,7 +28,7 @@ type Problem_Behavior
dataflow error. If the value already contained any dataflow error, that
error takes precedence.
attach_problem_after : Any -> Any -> Any
attach_problem_after decorated_value ~problem = case self of
attach_problem_after self decorated_value ~problem = case self of
Ignore ->
decorated_value
Report_Warning ->
@ -50,7 +50,7 @@ type Problem_Behavior
have been contained in the value - in such case the `decorated_value` is
not computed at all.
attach_problem_before : Any -> Any -> Any
attach_problem_before problem ~decorated_value = case self of
attach_problem_before self problem ~decorated_value = case self of
Ignore ->
decorated_value
Report_Warning ->
@ -79,7 +79,7 @@ type Problem_Behavior
expensive_computation
attach_problems_before : Vector -> Any -> Any
attach_problems_before problems ~decorated_value = case self of
attach_problems_before self problems ~decorated_value = case self of
Ignore ->
decorated_value
Report_Warning ->
@ -109,7 +109,7 @@ type Problem_Behavior
problem_behavior.attach_problems_after result <|
perform_post_process_checks_and_return_problems
attach_problems_after : Any -> Vector -> Any
attach_problems_after decorated_value ~problems = case self of
attach_problems_after self decorated_value ~problems = case self of
Ignore ->
decorated_value
Report_Warning ->

View File

@ -90,14 +90,14 @@ get_atom_fields atom = @Builtin_Method "Meta.get_atom_fields"
Returns a vector of field values of the given atom.
Atom.fields : Vector.Vector
Atom.fields = Vector.Vector (get_atom_fields self.value)
Atom.fields self = Vector.Vector (get_atom_fields self.value)
## UNSTABLE
ADVANCED
Returns a constructor value of the given atom.
Atom.constructor : Atom_Constructor
Atom.constructor = get_atom_constructor self.value
Atom.constructor self = get_atom_constructor self.value
# Polyglot methods
## PRIVATE
@ -114,7 +114,7 @@ get_polyglot_language value = @Builtin_Method "Meta.get_polyglot_language"
Returns the language with which a polyglot value is associated.
Polyglot.get_language : Language
Polyglot.get_language =
Polyglot.get_language self =
lang_str = get_polyglot_language self.value
if lang_str == "java" then Java else Unknown
@ -156,7 +156,7 @@ get_unresolved_symbol_scope symbol = @Builtin_Method "Meta.get_unresolved_symbol
Arguments:
- new_name: The new name for the unresolved symbol.
Unresolved_Symbol.rename : Text -> Any
Unresolved_Symbol.rename new_name =
Unresolved_Symbol.rename self new_name =
create_unresolved_symbol new_name self.scope
## UNSTABLE
@ -164,14 +164,14 @@ Unresolved_Symbol.rename new_name =
Returns the name of an unresolved symbol.
Unresolved_Symbol.name : Text
Unresolved_Symbol.name = get_unresolved_symbol_name self.value
Unresolved_Symbol.name self = get_unresolved_symbol_name self.value
## UNSTABLE
ADVANCED
Returns the definition scope of an unresolved symbol.
Unresolved_Symbol.scope : Any
Unresolved_Symbol.scope = get_unresolved_symbol_scope self.value
Unresolved_Symbol.scope self = get_unresolved_symbol_scope self.value
# Constructor methods
@ -208,14 +208,14 @@ new_atom constructor fields = @Builtin_Method "Meta.new_atom"
Returns a vector of field names defined by a constructor.
Constructor.fields : Vector.Vector
Constructor.fields = Vector.Vector (get_constructor_fields self.value)
Constructor.fields self = Vector.Vector (get_constructor_fields self.value)
## UNSTABLE
ADVANCED
Returns the name of a constructor.
Constructor.name : Text
Constructor.name = get_constructor_name self.value
Constructor.name self = get_constructor_name self.value
## UNSTABLE
ADVANCED
@ -226,7 +226,7 @@ Constructor.name = get_constructor_name self.value
- fields: A vector of arguments to pass to the constructor when creating the
new atom.
Constructor.new : Vector.Vector -> Any
Constructor.new fields = new_atom self.value fields.to_array
Constructor.new self fields = new_atom self.value fields.to_array
## UNSTABLE
@ -263,7 +263,7 @@ is_same_object value_1 value_2 = @Builtin_Method "Meta.is_same_object"
Arguments:
- typ: The type to check `self` against.
Any.is_a : Any -> Boolean
Any.is_a typ = is_a self typ
Any.is_a self typ = is_a self typ
## UNSTABLE
ADVANCED
@ -273,7 +273,7 @@ Any.is_a typ = is_a self typ
Arguments:
- typ: The type to check `self` against.
Any.is_an : Any -> Boolean
Any.is_an typ = is_a self typ
Any.is_an self typ = is_a self typ
## UNSTABLE
ADVANCED
@ -283,7 +283,7 @@ Any.is_an typ = is_a self typ
Arguments:
- typ: The type to check `self` against.
Base.Error.is_a : Any -> Boolean
Base.Error.is_a typ = self.is_an typ
Base.Error.is_a self typ = self.is_an typ
## UNSTABLE
ADVANCED
@ -293,7 +293,7 @@ Base.Error.is_a typ = self.is_an typ
Arguments:
- typ: The type to check `self` against.
Base.Error.is_an : Any -> Boolean
Base.Error.is_an typ = typ==Any || typ==Base.Error
Base.Error.is_an self typ = typ==Any || typ==Base.Error
## UNSTABLE
ADVANCED

View File

@ -19,7 +19,7 @@ type Project_Description
enso_project.root
root : File.File
root = File.new self.prim_root_file
root self = File.new self.prim_root_file
## Returns the root data directory of the project.
@ -28,7 +28,7 @@ type Project_Description
enso_project.data
data : File.File
data = self.root / "data"
data self = self.root / "data"
## Returns the name of the project.
@ -37,7 +37,7 @@ type Project_Description
enso_project.name
name : Text
name = self.prim_config.name
name self = self.prim_config.name
## Returns the namespace of the project.
@ -46,4 +46,4 @@ type Project_Description
enso_project.namespace
namespace : Text
namespace = self.prim_config.namespace
namespace self = self.prim_config.namespace

View File

@ -308,7 +308,7 @@ type Http
example_options = Examples.http_client.options "http://httpbin.org"
options : (Text | URI) -> Vector.Vector -> Response ! Request_Error
options uri (headers = []) =
options self uri (headers = []) =
req = Request.options uri headers
self.request req
@ -346,7 +346,7 @@ type Http
res = Examples.http_client.get "http://httpbin.org/bytes/1024"
res.body.to_file out_file
get : (Text | URI) -> Vector.Vector -> Response ! Request_Error
get uri (headers = []) =
get self uri (headers = []) =
req = Request.get uri headers
self.request req
@ -364,7 +364,7 @@ type Http
example_head = Examples.http_client.head "http://httpbin.org"
head : (Text | URI) -> Vector.Vector -> Response ! Request_Error
head uri (headers = []) =
head self uri (headers = []) =
req = Request.head uri headers
self.request req
@ -388,7 +388,7 @@ type Http
body = Body.Bytes "Hello".utf_8
Examples.http_client.post "http://httpbin.org/post" body [header_binary]
post : (Text | URI) -> Request_Body -> Vector.Vector -> Respoonse ! Request_Error
post uri body (headers = []) =
post self uri body (headers = []) =
req = Request.post uri body headers
self.request req
@ -425,7 +425,7 @@ type Http
form = [Form.text_field "name" "John Doe", Form.file_field "license.txt" (enso_project.root / "LICENSE")]
Examples.http_client.post_form "http://httpbin.org/post" form [Header.multipart_form_data]
post_form : (Text | URI) -> (Vector | Form) -> Vector.Vector -> Response ! Request_Error
post_form uri parts (headers = []) =
post_form self uri parts (headers = []) =
new_headers = [Header.application_x_www_form_urlencoded]
req = Request.post uri (Request_Body.Form parts.to_form) new_headers . with_headers headers
self.request req
@ -448,7 +448,7 @@ type Http
json = Json.parse '{"key":"val"}'
Examples.http_client.post_json "http://httpbin.org/post" json
post_json : (Text | URI) -> (Text | Json) -> Vector.Vector -> Response ! Request_Error
post_json uri body_json (headers = []) =
post_json self uri body_json (headers = []) =
new_headers = [Header.application_json]
req = Request.post uri (Request_Body.Json body_json) headers . with_headers new_headers
self.request req
@ -471,7 +471,7 @@ type Http
body = Body.Bytes "contents".utf_8
Examples.http_client.put "http://httpbin.org/post" body [header_binary]
put : (Text | URI) -> Request_Body -> Vector.Vector -> Respoonse ! Request_Error
put uri body (headers = []) =
put self uri body (headers = []) =
req = Request.put uri body headers
self.request req
@ -492,7 +492,7 @@ type Http
json = Json.parse '{"key":"val"}'
Examples.http_client.put_json "http://httpbin.org/post" json
put_json : (Text | URI) -> (Text | Json) -> Vector.Vector -> Response ! Request_Error
put_json uri body_json (headers = []) =
put_json self uri body_json (headers = []) =
new_headers = [Header.application_json]
req = Request.put uri (Request_Body.Json body_json) headers . with_headers new_headers
self.request req
@ -510,7 +510,7 @@ type Http
example_delete = Examples.http_client.delete "http://httpbin.org/delete"
delete : (Text | URI) -> Vector.Vector -> Response ! Request_Error
delete uri (headers = []) =
delete self uri (headers = []) =
req = Request.delete uri headers
self.request req
@ -595,7 +595,7 @@ type Http
http = Http.new (timeout = 30.seconds)
http.request req
request : Request -> Response ! Request_Error
request req =
request self req =
handle_request_error =
Panic.catch_java Any handler=(err-> Error.throw (Request_Error 'IllegalArgumentException' err.getMessage))
Panic.recover Any <| handle_request_error <|
@ -657,7 +657,7 @@ type Http
Build an HTTP client.
internal_http_client : HttpClient
internal_http_client =
internal_http_client self =
builder = HttpClient.newBuilder
# timeout
if self.timeout.is_date then Panic.throw (Time.Time_Error "Connection timeout does not support date intervals") else
@ -699,7 +699,7 @@ type Request_Error error_type message
## UNSTABLE
Convert a request error to a human-readable form.
Request_Error.to_display_text =
Request_Error.to_display_text self =
description_text = case self.message of
Nothing -> ""
_ -> " " + self.message

View File

@ -68,7 +68,7 @@ type Form
example_to_form = Form.new [Part "foo" (Part_Text "bar")] . to_form
to_form : Form
to_form = self
to_form self = self
## Convert Vector to a Form.
@ -81,7 +81,7 @@ type Form
part_1 = Form.text_field "Foo" "bar"
part_2 = Form.text_field "Baz" "quux"
[part_1, part_2].to_form
Vector.Vector.to_form = Form self
Vector.Vector.to_form self = Form self
## The key-value element of the form.
type Part

View File

@ -178,5 +178,5 @@ type Header
example_header_eq =
(Header.new "My_Header" "foo") == (Header.new "My_Header" "bar")
== : Header -> Boolean
== that = (self.name.equals_ignore_case that.name) && self.value==that.value
== self that = (self.name.equals_ignore_case that.name) && self.value==that.value

View File

@ -151,7 +151,7 @@ type Request
example_with_header = Request.delete.with_header "Foo" "bar"
with_header : Text -> Text -> Request
with_header key val =
with_header self key val =
new_header = Header.new key val
update_header p h = case p of
Pair acc True -> Pair (acc + [h]) True
@ -175,7 +175,7 @@ type Request
example_with_headers = Request.delete.with_headers []
with_headers : [Header] -> Request
with_headers new_headers =
with_headers self new_headers =
update_header req new_header = req.with_header new_header.name new_header.value
new_headers.fold self update_header
@ -194,7 +194,7 @@ type Request
example_with_body =
Request.post (URI.parse "http://example.com") Request_Body.Empty |> _.with_body Request_Body.Empty
with_body : Request_Body -> Request
with_body new_body = Request self.method self.uri self.headers new_body
with_body self new_body = Request self.method self.uri self.headers new_body
## Set the body text in the request encoded as "application/json".
@ -212,7 +212,7 @@ type Request
example_with_json =
Request.post (URI.parse "http://example.com") Request_Body.Empty |> _.with_json '{ "a": "b" }'
with_json : (Text | Json) -> Request
with_json json_body =
with_json self json_body =
new_body = Request_Body.Json json_body
Request self.method self.uri self.headers new_body . with_headers [Header.application_json]
@ -230,6 +230,6 @@ type Request
example_delete =
Request.delete (URI.parse "http://example.com") . with_form []
with_form : (Vector | Form) -> Request
with_form parts =
with_form self parts =
new_body = Request_Body.Form parts.to_form
Request self.method self.uri self.headers new_body . with_headers [Header.application_x_www_form_urlencoded]

View File

@ -28,7 +28,7 @@ type Response
example_headers = Examples.get_response.headers
headers : Vector.Vector
headers =
headers self =
header_entries = Vector.Vector (Http_Utils.get_headers self.internal_http_response.headers)
header_entries.map e-> Header.new e.getKey e.getValue
@ -42,7 +42,7 @@ type Response
example_body = Examples.get_response.body
body : Response_Body
body = Response_Body.Body (Vector.Vector self.internal_http_response.body)
body self = Response_Body.Body (Vector.Vector self.internal_http_response.body)
## Get the response status code.
@ -54,7 +54,7 @@ type Response
example_code = Examples.get_response.code
code : Status_Code
code = Status_Code.Status_Code self.internal_http_response.statusCode
code self = Status_Code.Status_Code self.internal_http_response.statusCode
## Convert the response to JSON.
@ -66,5 +66,5 @@ type Response
example_to_json = Examples.get_response.to_json
to_json : Json.Object
to_json = Json.from_pairs [["type", "Response"], ["headers", self.headers], ["body", self.body], ["code", self.code]]
to_json self = Json.from_pairs [["type", "Response"], ["headers", self.headers], ["body", self.body], ["code", self.code]]

View File

@ -20,7 +20,7 @@ type Body
example_to_text = Examples.get_geo_data.to_text
to_text : Text
to_text = Text.from_utf_8 self.bytes
to_text self = Text.from_utf_8 self.bytes
## Convert response body to Json.
@ -31,7 +31,7 @@ type Body
example_to_text = Examples.get_geo_data.to_json
to_json : Json
to_json = Json.parse self.to_text
to_json self = Json.parse self.to_text
## Write response body to a File.
@ -48,7 +48,7 @@ type Body
example_to_file =
Examples.get_geo_data.to_file Examples.scratch_file
to_file : File -> File
to_file file =
to_file self file =
self.bytes.write_bytes file
file

View File

@ -36,7 +36,7 @@ parse text =
example_parse = "http://example.com".to_uri
Text.to_uri : URI ! Syntax_Error
Text.to_uri = parse self
Text.to_uri self = parse self
type URI
@ -57,7 +57,7 @@ type URI
example_to_uri = Examples.uri.to_uri
to_uri : URI
to_uri = self
to_uri self = self
## Get the scheme part of this URI.
@ -68,7 +68,7 @@ type URI
example_scheme = Examples.uri.scheme
scheme : Text ! Nothing
scheme = Internal.handle_nothing self.internal_uri.getScheme
scheme self = Internal.handle_nothing self.internal_uri.getScheme
## Get the user info part of this URI.
@ -79,7 +79,7 @@ type URI
example_user_info = Examples.uri.user_info
user_info : Text ! Nothing
user_info = Internal.handle_nothing self.internal_uri.getUserInfo
user_info self = Internal.handle_nothing self.internal_uri.getUserInfo
## Get the host part of this URI.
@ -90,7 +90,7 @@ type URI
example_host = Examples.uri.host
host : Text ! Nothing
host = Internal.handle_nothing self.internal_uri.getHost
host self = Internal.handle_nothing self.internal_uri.getHost
## Get the authority (user info and host) part of this URI.
@ -101,7 +101,7 @@ type URI
example_authority = Examples.uri.authority
authority : Text ! Nothing
authority = Internal.handle_nothing self.internal_uri.getAuthority
authority self = Internal.handle_nothing self.internal_uri.getAuthority
## Get the port part of this URI.
@ -112,7 +112,7 @@ type URI
example_port = Examples.uri.port
port : Text ! Nothing
port =
port self =
port_number = self.internal_uri.getPort
Internal.handle_nothing <|
if port_number == -1 then Nothing else port_number.to_text
@ -126,7 +126,7 @@ type URI
example_path = Examples.uri.path
path : Text ! Nothing
path = Internal.handle_nothing self.internal_uri.getPath
path self = Internal.handle_nothing self.internal_uri.getPath
## Get the query part of this URI.
@ -137,7 +137,7 @@ type URI
example_query = Examples.uri.query
query : Text ! Nothing
query = Internal.handle_nothing self.internal_uri.getQuery
query self = Internal.handle_nothing self.internal_uri.getQuery
## Get the fragment part of this URI.
@ -148,37 +148,37 @@ type URI
example_fragment = Examples.uri.fragment
fragment : Text ! Nothing
fragment = Internal.handle_nothing self.internal_uri.getFragment
fragment self = Internal.handle_nothing self.internal_uri.getFragment
## ADVANCED
Get the unescaped user info part of this URI.
raw_user_info : Text ! Nothing
raw_user_info = Internal.handle_nothing self.internal_uri.getRawUserInfo
raw_user_info self = Internal.handle_nothing self.internal_uri.getRawUserInfo
## ADVANCED
Get the unescaped authority part of this URI.
raw_authority : Text ! Nothing
raw_authority = Internal.handle_nothing self.internal_uri.getRawAuthority
raw_authority self = Internal.handle_nothing self.internal_uri.getRawAuthority
## ADVANCED
Get the unescaped path part of this URI.
raw_path : Text ! Nothing
raw_path = Internal.handle_nothing self.internal_uri.getRawPath
raw_path self = Internal.handle_nothing self.internal_uri.getRawPath
## ADVANCED
Get the unescaped query part of this URI.
raw_query : Text ! Nothing
raw_query = Internal.handle_nothing self.internal_uri.getRawQuery
raw_query self = Internal.handle_nothing self.internal_uri.getRawQuery
## ADVANCED
Get the unescaped fragment part of this URI.
raw_fragment : Text ! Nothing
raw_fragment = Internal.handle_nothing self.internal_uri.getRawFragment
raw_fragment self = Internal.handle_nothing self.internal_uri.getRawFragment
## Convert this URI to text.
@ -189,7 +189,7 @@ type URI
example_to_text = Examples.uri.to_text
to_text : Text
to_text = self.internal_uri.toString
to_text self = self.internal_uri.toString
## Convert a URI to JSON.
@ -201,7 +201,7 @@ type URI
example_to_json = Examples.uri.to_json
to_json : Json.String
to_json = Json.String self.to_text
to_json self = Json.String self.to_text
## Check if this URI is equal to another URI.
@ -212,4 +212,4 @@ type URI
example_eq = "https://example.com".to_uri == "http://example.org".to_uri
== : URI -> Boolean
== that = self.internal_uri.equals that.internal_uri
== self that = self.internal_uri.equals that.internal_uri

View File

@ -17,7 +17,7 @@ type Nothing
1.is_nothing
is_nothing : Boolean
is_nothing = True
is_nothing self = True
## UNSTABLE
If this is Nothing then returns `function`.
@ -27,4 +27,4 @@ type Nothing
"Hello".if_nothing ""
if_nothing : Any -> Any
if_nothing ~function = function
if_nothing self ~function = function

View File

@ -19,7 +19,7 @@ primitive_get_stack_trace = @Builtin_Method "Runtime.primitive_get_stack_trace"
resulting vector is such that the top stack frame is the first element.
get_stack_trace : Vector.Vector Stack_Trace_Element
get_stack_trace =
prim_stack = self.primitive_get_stack_trace
prim_stack = primitive_get_stack_trace
stack_with_prims = Vector.Vector prim_stack
stack = stack_with_prims.map wrap_primitive_stack_trace_element
# drop this frame and the one from `Runtime.primitive_get_stack_trace`

View File

@ -11,38 +11,38 @@ type Source_Location
## UNSTABLE
Pretty prints the location.
to_text : Text
to_text =
to_text self =
'(Source_Location ' + self.formatted_coordinates + ')'
## UNSTABLE
Returns the 1-based line index of the start of this code range.
start_line : Integer
start_line = self.prim_location.getStartLine
start_line self = self.prim_location.getStartLine
## UNSTABLE
Returns the 1-based line index of the end of this code range.
end_line : Integer
end_line = self.prim_location.getEndLine
end_line self = self.prim_location.getEndLine
## UNSTABLE
Returns the 1-based column index of the start of this code range.
start_column : Integer
start_column = self.prim_location.getStartColumn
start_column self = self.prim_location.getStartColumn
## UNSTABLE
Returns the 1-based column index of the end of this code range.
end_column : Integer
end_column = self.prim_location.getEndColumn
end_column self = self.prim_location.getEndColumn
## UNSTABLE
Returns a pretty-printed location (file and line info).
formatted_coordinates : Text
formatted_coordinates =
formatted_coordinates self =
start_line = self.start_line
end_line = self.end_line
indices = case start_line == end_line of
@ -64,4 +64,4 @@ type Source_Location
Return the source file corresponding to this location.
file : File.File
file = File.new self.prim_location.getSource.getPath
file self = File.new self.prim_location.getSource.getPath

View File

@ -12,7 +12,7 @@ type Ref
(Ref.new 0) . get
get : Any
get ref = @Builtin_Method "Ref.get"
get self = @Builtin_Method "Ref.get"
## Puts a new value into this reference, returning the old value.
@ -24,7 +24,7 @@ type Ref
(Ref.new 0) . put 10
put : Any -> Any
put new_value = @Builtin_Method "Ref.put"
put self new_value = @Builtin_Method "Ref.put"
## Creates a new reference containing the provided value.

View File

@ -46,7 +46,7 @@ type Managed_Resource
Forces finalization of a managed resource using the registered finalizer,
even if the resource is still reachable.
finalize : Nothing
finalize = @Builtin_Method "Managed_Resource.finalize"
finalize self = @Builtin_Method "Managed_Resource.finalize"
## ADVANCED
@ -57,7 +57,7 @@ type Managed_Resource
- action: The action that will be applied to the resource managed by
resource.
with : (Any -> Any) -> Any
with ~action = @Builtin_Method "Managed_Resource.with"
with self ~action = @Builtin_Method "Managed_Resource.with"
## ADVANCED
@ -65,4 +65,4 @@ type Managed_Resource
finalization step for this resource, effectively removing it from the
managed resources system.
take : Managed_Resource -> Any
take = @Builtin_Method "Managed_Resource.take"
take self = @Builtin_Method "Managed_Resource.take"

View File

@ -207,7 +207,7 @@ type File
action = stream -> stream.write_bytes "hello".utf_8
file.with_output_stream [Option.Create, Option.Write] action
with_output_stream : Vector.Vector -> (Output_Stream -> Any ! File_Error) -> Any ! File_Error
with_output_stream open_options action =
with_output_stream self open_options action =
Resource.bracket (self.new_output_stream open_options) (_.close) action
## PRIVATE
@ -219,7 +219,7 @@ type File
- options: A vector of `File.Option` objects determining how to open
the stream. These options set the access properties of the stream.
output_stream : Vector.Vector -> Output_Stream
output_stream options = @Builtin_Method "File.output_stream"
output_stream self options = @Builtin_Method "File.output_stream"
## PRIVATE
@ -230,7 +230,7 @@ type File
- open_options: A vector of `File.Option` objects determining how to open
the stream. These options set the access properties of the stream.
input_stream : Vector.Vector -> Input_Stream
input_stream options = @Builtin_Method "File.input_stream"
input_stream self options = @Builtin_Method "File.input_stream"
## Creates a new input stream for this file and runs the specified action
on it.
@ -255,7 +255,7 @@ type File
action = stream -> stream.read_all_bytes
file.with_input_stream [Option.Create, Option.Read] action
with_input_stream : Vector.Vector -> (Input_Stream -> Any ! File_Error) -> Any ! File_Error
with_input_stream open_options action =
with_input_stream self open_options action =
Resource.bracket (self.new_input_stream open_options) (_.close) action
## Reads all bytes in this file into a byte vector.
@ -267,7 +267,7 @@ type File
example_read_bytes = Examples.csv.read_bytes
read_bytes : Vector.Vector ! File_Error
read_bytes =
read_bytes self =
opts = [Option.Read]
self.with_input_stream opts (_.read_all_bytes)
@ -288,7 +288,7 @@ type File
example_read = Examples.csv.read
read_text : Encoding -> Problem_Behavior -> Text ! File_Error
read_text (encoding=Encoding.utf_8) (on_problems=Report_Warning) =
read_text self (encoding=Encoding.utf_8) (on_problems=Report_Warning) =
bytes = self.read_bytes
Text.from_bytes bytes encoding on_problems
@ -304,10 +304,10 @@ type File
example_append = Examples.data_dir / "scratch_file"
/ : (Text | File) -> File
/ subpath = self.resolve subpath
/ self subpath = self.resolve subpath
resolve : (Text | File) -> File
resolve = @Builtin_Method "File.resolve"
resolve self = @Builtin_Method "File.resolve"
## A File to JSON conversion.
@ -318,7 +318,7 @@ type File
example_to_json = Examples.csv.to_json
to_json : Json.Object
to_json = Json.from_pairs [["type", "File"], ["path", self.path]]
to_json self = Json.from_pairs [["type", "File"], ["path", self.path]]
## Checks whether the file exists.
@ -329,7 +329,7 @@ type File
example_exists = Examples.csv.exists
exists : Boolean
exists = @Builtin_Method "File.exists"
exists self = @Builtin_Method "File.exists"
## Gets the creation time of a file.
@ -340,7 +340,7 @@ type File
example_exists = Examples.csv.creation_time
creation_time : Time ! File_Error
creation_time =
creation_time self =
handle_java_exceptions self <|
Time (self.creation_time_builtin)
@ -350,7 +350,7 @@ type File
Recommended to use `File.creation_time` instead which handles potential
exceptions.
creation_time_builtin : File -> ZonedDateTime
creation_time_builtin = @Builtin_Method "File.creation_time_builtin"
creation_time_builtin self = @Builtin_Method "File.creation_time_builtin"
## Gets the last modified time of a file.
@ -361,7 +361,7 @@ type File
example_exists = Examples.csv.last_modified_time
last_modified_time : Time ! File_Error
last_modified_time =
last_modified_time self =
handle_java_exceptions self <|
Time (self.last_modified_time_builtin)
@ -371,7 +371,7 @@ type File
Recommended to use `File.last_modified_time` instead which handles
potential exceptions.
last_modified_time_builtin : ZonedDateTime
last_modified_time_builtin = @Builtin_Method "File.last_modified_time_builtin"
last_modified_time_builtin self = @Builtin_Method "File.last_modified_time_builtin"
## Gets the POSIX permissions associated with the file.
@ -382,7 +382,7 @@ type File
example_permissions = Examples.csv.posix_permissions.group_read
posix_permissions : File_Permissions
posix_permissions =
posix_permissions self =
File_Permissions.from_java_set self.posix_permissions_builtin
## PRIVATE
@ -392,7 +392,7 @@ type File
potential exceptions and converts an Enso representation of the
permissions.
posix_permissions_builtin : Set
posix_permissions_builtin = @Builtin_Method "File.posix_permissions_builtin"
posix_permissions_builtin self = @Builtin_Method "File.posix_permissions_builtin"
## Checks whether the file exists and is a directory.
@ -403,7 +403,7 @@ type File
example_is_directory = Examples.csv.is_directory
is_directory : Boolean
is_directory = @Builtin_Method "File.is_directory"
is_directory self = @Builtin_Method "File.is_directory"
## Creates the directory represented by this file if it did not exist.
@ -417,7 +417,7 @@ type File
example_is_directory =
(Examples.data_dir / "my_directory") . create_directory
create_directory : Nothing
create_directory = @Builtin_Method "File.create_directory"
create_directory self = @Builtin_Method "File.create_directory"
## Checks whether the file exists and is a regular file.
@ -433,7 +433,7 @@ type File
example_is_regular_file = Examples.csv.is_regular_file
is_regular_file : Boolean
is_regular_file = @Builtin_Method "File.is_regular_file"
is_regular_file self = @Builtin_Method "File.is_regular_file"
## Resolves the parent filesystem node of this file.
@ -444,7 +444,7 @@ type File
example_parent = Examples.csv.parent
parent : File
parent = @Builtin_Method "File.parent"
parent self = @Builtin_Method "File.parent"
## Returns the path of this file.
@ -455,7 +455,7 @@ type File
example_path = Examples.csv.path
path : Text
path = @Builtin_Method "File.path"
path self = @Builtin_Method "File.path"
## Returns the name of this file.
@ -466,7 +466,7 @@ type File
example_name = Examples.csv.name
name : Text
name = @Builtin_Method "File.name"
name self = @Builtin_Method "File.name"
## Returns the extension of the file.
@ -477,7 +477,7 @@ type File
Examples.csv.extension == ".csv"
extension : Text
extension =
extension self =
name = self.name
last_dot = name.location_of "." mode=Matching_Mode.Last
if last_dot.is_nothing then "" else
@ -494,7 +494,7 @@ type File
example_absolute = Examples.csv.absolute
absolute : File
absolute = @Builtin_Method "File.absolute"
absolute self = @Builtin_Method "File.absolute"
## Checks is this file's path is absolute.
@ -505,7 +505,7 @@ type File
example_is_absolute = Examples.csv.is_absolute
is_absolute : Boolean
is_absolute = @Builtin_Method "File.is_absolute"
is_absolute self = @Builtin_Method "File.is_absolute"
## Normalizes the filepath.
@ -516,7 +516,7 @@ type File
example_normalize = Examples.csv.normalize
normalize : File
normalize = @Builtin_Method "File.normalize"
normalize self = @Builtin_Method "File.normalize"
## Checks if this file has the same `path` as `that`.
@ -527,7 +527,7 @@ type File
example_eq = Examples.csv == Examples.scratch_file
== : File -> Boolean
== that = @Builtin_Method "File.=="
== self that = @Builtin_Method "File.=="
## Deletes the file.
@ -544,7 +544,7 @@ type File
file.write_text "hello"
file.delete
delete : Nothing ! File_Error
delete =
delete self =
handle_java_exceptions self self.delete_builtin
## PRIVATE
@ -552,7 +552,7 @@ type File
Builtin method that deletes the file.
Recommended to use `File.delete` instead which handles potential exceptions.
delete_builtin : Nothing
delete_builtin = @Builtin_Method "File.delete"
delete_builtin self = @Builtin_Method "File.delete"
## Moves the file to the specified destination.
@ -561,7 +561,7 @@ type File
- replace_existing: specifies if the operation should proceed if the
destination file already exists. Defaults to `False`.
copy_to : File -> Boolean -> Nothing ! File_Error
copy_to destination replace_existing=False =
copy_to self destination replace_existing=False =
handle_java_exceptions self <| case replace_existing of
True ->
copy_options = Array.new_1 StandardCopyOption.REPLACE_EXISTING
@ -573,7 +573,7 @@ type File
Builtin method that copies this file to a new destination.
Recommended to use `File.copy_to` instead which handles potential exceptions.
copy_builtin : File -> Array Any -> Nothing
copy_builtin destination copy_options = @Builtin_Method "File.copy_builtin"
copy_builtin self destination copy_options = @Builtin_Method "File.copy_builtin"
## Moves the file to the specified destination.
@ -582,7 +582,7 @@ type File
- replace_existing: specifies if the operation should proceed if the
destination file already exists. Defaults to `False`.
move_to : File -> Boolean -> Nothing ! File_Error
move_to destination replace_existing=False =
move_to self destination replace_existing=False =
handle_java_exceptions self <| case replace_existing of
True ->
copy_options = Array.new_1 StandardCopyOption.REPLACE_EXISTING
@ -594,7 +594,7 @@ type File
Builtin method that moves this file to a new destination.
Recommended to use `File.move_to` instead which handles potential exceptions.
move_builtin : File -> Array Any -> Nothing
move_builtin destination copy_options = @Builtin_Method "File.move_builtin"
move_builtin self destination copy_options = @Builtin_Method "File.move_builtin"
## Deletes the file if it exists on disk.
@ -608,7 +608,7 @@ type File
example_del_if_exists = Examples.scratch_file.delete_if_exists
delete_if_exists : Nothing ! File_Error
delete_if_exists = if self.exists then self.delete else Nothing
delete_if_exists self = if self.exists then self.delete else Nothing
## ADVANCED
@ -621,7 +621,7 @@ type File
The returned stream should be closed as soon as it is not used anymore.
The `with_input_stream` method should be preferred whenever possible.
new_input_stream : Vector.Vector -> Input_Stream ! File_Error
new_input_stream open_options =
new_input_stream self open_options =
opts = open_options . map (_.to_java) . to_array
stream = handle_java_exceptions self (self.input_stream opts)
resource = Managed_Resource.register stream close_stream
@ -638,7 +638,7 @@ type File
The returned stream should be closed as soon as it is not used anymore.
The `with_output_stream` method should be preferred whenever possible.
new_output_stream : Vector.Vector -> Output_Stream ! File_Error
new_output_stream open_options =
new_output_stream self open_options =
opts = open_options . map (_.to_java) . to_array
stream = handle_java_exceptions self <|
self.output_stream opts
@ -650,13 +650,13 @@ type File
Reads last `n` bytes from the file (or less if the file is too small) and
returns a vector of bytes.
read_last_bytes : Integer -> Vector ! File_Error
read_last_bytes n =
read_last_bytes self n =
handle_java_exceptions self <|
Vector.Vector (self.read_last_bytes_builtin n)
## PRIVATE
read_last_bytes_builtin : Integer -> Array
read_last_bytes_builtin n = @Builtin_Method "File.read_last_bytes_builtin"
read_last_bytes_builtin self n = @Builtin_Method "File.read_last_bytes_builtin"
## Lists files contained in the directory denoted by this file.
@ -711,7 +711,7 @@ type File
example_list_md_files =
Examples.data_dir.list name_filter="**.{txt,md}" recursive=True
list : Text -> Boolean -> Vector.Vector File
list name_filter=Nothing recursive=False =
list self name_filter=Nothing recursive=False =
all_files = case recursive of
True -> list_descendants self
False -> self.list_immediate_children
@ -729,32 +729,32 @@ type File
Checks if `self` is a child path of `other`.
is_child_of : File -> Boolean
is_child_of other = self.starts_with other
is_child_of self other = self.starts_with other
## UNSTABLE
Transforms `child` to a relative path with respect to `self`.
relativize : File -> Boolean
relativize child = @Builtin_Method "File.relativize"
relativize self child = @Builtin_Method "File.relativize"
## PRIVATE
Utility function that lists immediate children of a directory.
list_immediate_children : Vector.Vector File
list_immediate_children = Vector.Vector (self.list_immediate_children_array)
list_immediate_children self = Vector.Vector (self.list_immediate_children_array)
## PRIVATE
Utility function that lists immediate children of a directory.
list_immediate_children_array : Array File
list_immediate_children_array = @Builtin_Method "File.list_immediate_children_array"
list_immediate_children_array self = @Builtin_Method "File.list_immediate_children_array"
## PRIVATE
Return the absolute path of this File
to_text : Text
to_text = self.absolute . path
to_text self = self.absolute . path
## An output stream, allowing for interactive writing of contents into an
open file.
@ -790,7 +790,7 @@ type Output_Stream
out_stream.write_bytes "hello".utf_8
out_stream.close
write_bytes : Vector.Vector -> Nothing ! File_Error
write_bytes contents = self.stream_resource . with java_stream->
write_bytes self contents = self.stream_resource . with java_stream->
handle_java_exceptions self.file <|
java_stream.write contents.to_array
java_stream.flush
@ -815,7 +815,7 @@ type Output_Stream
out_stream = file.new_output_stream [Option.Create]
out_stream.close
close : Nothing
close = self.stream_resource . finalize
close self = self.stream_resource . finalize
## PRIVATE
@ -827,13 +827,13 @@ type Output_Stream
Useful when integrating with polyglot functions requiring an
`OutputStream` as an argument.
with_java_stream : (Java_Output_Stream -> Any) -> Any
with_java_stream f = self.stream_resource . with f
with_java_stream self f = self.stream_resource . with f
## PRIVATE
Runs an action with a `ReportingStreamEncoder` encoding data to the
output stream with the specified encoding.
with_stream_encoder : Encoding -> Problem_Behavior -> (ReportingStreamEncoder -> Any) -> Any
with_stream_encoder encoding on_problems action = self.with_java_stream java_stream->
with_stream_encoder self encoding on_problems action = self.with_java_stream java_stream->
## We ignore any warnings raised by the `bytes` method, because if the
original Unicode replacement character failed to encode, the `bytes`
method will have replaced it with the simple `?` sign which should be
@ -878,7 +878,7 @@ type Input_Stream
in_stream.close
bytes
read_all_bytes : Vector.Vector ! File_Error
read_all_bytes = self.stream_resource . with java_stream->
read_all_bytes self = self.stream_resource . with java_stream->
handle_java_exceptions self.file <|
Vector.Vector java_stream.readAllBytes
@ -908,7 +908,7 @@ type Input_Stream
in_stream.close
bytes
read_n_bytes : Integer -> Vector.Vector ! File_Error
read_n_bytes n = self.stream_resource . with java_stream->
read_n_bytes self n = self.stream_resource . with java_stream->
handle_java_exceptions self.file <|
bytes = java_stream.readNBytes n
Vector.Vector bytes
@ -933,7 +933,7 @@ type Input_Stream
in_stream.close
bytes
read_byte : Integer ! File_Error
read_byte = self.stream_resource . with java_stream->
read_byte self = self.stream_resource . with java_stream->
handle_java_exceptions self.file <|
java_stream.read
@ -956,7 +956,7 @@ type Input_Stream
in_stream = file.new_input_stream [Option.Read]
in_stream.close
close : Nothing
close = self.stream_resource . finalize
close self = self.stream_resource . finalize
## PRIVATE
@ -968,13 +968,13 @@ type Input_Stream
Useful when integrating with polyglot functions requiring an
`InputStream` as an argument.
with_java_stream : (Java_Input_Stream -> Any) -> Any
with_java_stream f = self.stream_resource . with f
with_java_stream self f = self.stream_resource . with f
## PRIVATE
Runs an action with a `ReportingStreamDecoder` decoding data from the
input stream with the specified encoding.
with_stream_decoder : Encoding -> Problem_Behavior -> (ReportingStreamDecoder -> Any) -> Any
with_stream_decoder encoding on_problems action = self.stream_resource . with java_stream->
with_stream_decoder self encoding on_problems action = self.stream_resource . with java_stream->
java_charset = encoding.to_java_charset
results = Encoding_Utils.with_stream_decoder java_stream java_charset action
problems = Vector.Vector results.problems . map Encoding_Error
@ -1027,7 +1027,7 @@ type File_Error
Convert the File error to a human-readable format.
to_display_text : Text
to_display_text = case self of
to_display_text self = case self of
File_Not_Found file -> "The file at " + file.path + " does not exist."
IO_Error file msg -> msg.to_text + " (" + file.path + ")."
File_Already_Exists_Error file -> "The file at "+file.path+" already exists."
@ -1087,7 +1087,7 @@ get_file path = @Builtin_Method "File.get_file"
If another error occurs, such as access denied, an `IO_Error` is raised.
Otherwise, the file is created with the encoded text written to it.
Text.write : (File|Text) -> Encoding -> Existing_File_Behavior -> Problem_Behavior -> Nothing ! Encoding_Error | Illegal_Argument_Error | File_Not_Found | IO_Error | File_Already_Exists_Error
Text.write path encoding=Encoding.utf_8 on_existing_file=Existing_File_Behavior.Backup on_problems=Report_Warning =
Text.write self path encoding=Encoding.utf_8 on_existing_file=Existing_File_Behavior.Backup on_problems=Report_Warning =
bytes = self.bytes encoding on_problems
file = new path
on_existing_file.write file stream->
@ -1121,7 +1121,7 @@ Text.write path encoding=Encoding.utf_8 on_existing_file=Existing_File_Behavior.
[36, -62, -93, -62, -89, -30, -126, -84, -62, -94].write_bytes Examples.scratch_file.write_bytes Examples.scratch_file Existing_File_Behavior.Append
Vector.Vector.write_bytes : (File|Text) -> Existing_File_Behavior -> Nothing ! Illegal_Argument_Error | File_Not_Found | IO_Error | File_Already_Exists_Error
Vector.Vector.write_bytes path on_existing_file=Existing_File_Behavior.Backup =
Vector.Vector.write_bytes self path on_existing_file=Existing_File_Behavior.Backup =
Panic.catch Unsupported_Argument_Types handler=(Error.throw (Illegal_Argument_Error "Only Vectors consisting of bytes (integers in the range from -128 to 127) are supported by the `write_bytes` method.")) <|
## Convert to a byte array before writing - and fail early if there is any problem.
byte_array = Array_Utils.ensureByteArray self.to_array

View File

@ -39,7 +39,7 @@ type Existing_File_Behavior
The `action` may not be run at all in case the `Error` behavior is
selected.
write : File -> (Output_Stream -> Nothing) -> Nothing ! File_Not_Found | IO_Error | File_Already_Exists_Error
write file action =
write self file action =
case self of
Overwrite -> file.with_output_stream [Option.Write, Option.Create, Option.Truncate_Existing] action
Append -> file.with_output_stream [Option.Write, Option.Create, Option.Append] action

View File

@ -18,7 +18,7 @@ type File_Permissions
## Converts the Enso atom to its Java enum counterpart.
to_java : Vector PosixFilePermission
to_java =
to_java self =
result = Vector.new_builder
if self.owner.contains Read then
result.append PosixFilePermission.OWNER_READ
@ -42,39 +42,39 @@ type File_Permissions
## Checks if the given file can be read by the owner.
owner_read : Boolean
owner_read = self.owner.contains Read
owner_read self = self.owner.contains Read
## Checks if the given file can be written by the owner.
owner_write : Boolean
owner_write = self.owner.contains Write
owner_write self = self.owner.contains Write
## Checks if the given file can be executed by the owner.
owner_execute : Boolean
owner_execute = self.owner.contains Execute
owner_execute self = self.owner.contains Execute
## Checks if the given file can be read by the group.
group_read : Boolean
group_read = self.group.contains Read
group_read self = self.group.contains Read
## Checks if the given file can be written by the group.
group_write : Boolean
group_write = self.group.contains Write
group_write self = self.group.contains Write
## Checks if the given file can be executed by the group.
group_execute : Boolean
group_execute = self.group.contains Execute
group_execute self = self.group.contains Execute
## Checks if the given file can be read by others.
others_read : Boolean
others_read = self.others.contains Read
others_read self = self.others.contains Read
## Checks if the given file can be written by others.
others_write : Boolean
others_write = self.others.contains Write
others_write self = self.others.contains Write
## Checks if the given file can be executed by others.
others_execute : Boolean
others_execute = self.others.contains Execute
others_execute self = self.others.contains Execute
## Converts a Java `Set` of Java `PosixFilePermission` to `File_Permissions`.
from_java_set java_set =

View File

@ -47,7 +47,7 @@ type Option
Convert this object into a representation understandable by the JVM.
to_java : StandardOpenOption
to_java = case self of
to_java self = case self of
Append -> StandardOpenOption.APPEND
Create -> StandardOpenOption.CREATE
Create_New -> StandardOpenOption.CREATE_NEW

View File

@ -80,7 +80,7 @@ type Builder
builder = Process.new_builder "echo"
builder.set_arguments ["hello, world!"]
set_arguments : Vector.Vector Text -> Builder
set_arguments arguments = Builder self.command arguments self.stdin
set_arguments self arguments = Builder self.command arguments self.stdin
## UNSTABLE
@ -99,7 +99,7 @@ type Builder
builder = Process.new_builder "echo"
builder.set_stdin "hello, world!"
set_stdin : Text -> Builder
set_stdin stdin = Builder self.command self.arguments stdin
set_stdin self stdin = Builder self.command self.arguments stdin
## UNSTABLE
@ -115,7 +115,7 @@ type Builder
with_args = builder.set_arguments ["hello, world!"]
with_args.create
create : Result
create =
create self =
result = System.create_process self.command self.arguments.to_array self.stdin redirect_in=False redirect_out=False redirect_err=False
Result (Exit_Code.from_number result.exit_code) result.stdout result.stderr

View File

@ -21,7 +21,7 @@ type Exit_Code
example_to_number = Exit_Code.Exit_Success.to_number
to_number : Integer
to_number = case self of
to_number self = case self of
Exit_Success -> 0
Exit_Failure code -> code

View File

@ -13,14 +13,14 @@ type Warning
Returns the warning value usually its explanation or other contents.
value : Any
value = @Builtin_Method "Warning.value"
value self = @Builtin_Method "Warning.value"
## UNSTABLE
ADVANCED
A stack trace for the original warning creation.
origin : Vector.Vector Stack_Trace_Element
origin = @Builtin_Method "Warning.origin"
origin self = @Builtin_Method "Warning.origin"
## UNSTABLE
ADVANCED
@ -39,7 +39,7 @@ type Warning
- The standard library methods reassign warnings such that their dataflow
nature is preserved.
reassignments : Vector.Vector Stack_Trace_Element
reassignments =
reassignments self =
Vector.Vector self.get_reassignments . map r->
loc = case Polyglot.has_source_location r of
False -> Nothing
@ -51,7 +51,7 @@ type Warning
Builtin method for getting the list of locations where the warnings was reassigned.
Should use `Warning.reassignments` instead.
get_reassignments : Any
get_reassignments = @Builtin_Method "Warning.get_reassignments"
get_reassignments self = @Builtin_Method "Warning.get_reassignments"
## PRIVATE

View File

@ -17,6 +17,6 @@ type Client_Certificate
- sslkey: points to the client key file.
- sslpass: password for the client key file.
properties : Vector
properties =
properties self =
base = [Pair 'sslcert' (File.new self.cert_file).absolute.path, Pair 'sslkey' (File.new self.key_file).absolute.path]
if self.key_password == "" then base else base + [Pair 'sslpassword' self.key_password]

View File

@ -45,7 +45,7 @@ type Connection
Arguments:
- name: name of the table to access
access_table : Text -> Database_Table
access_table name = handle_sql_errors <|
access_table self name = handle_sql_errors <|
columns = self.fetch_columns name
Database_Table.make_table self name columns
@ -54,12 +54,12 @@ type Connection
The connection is not usable afterwards.
close : Nothing
close =
close self =
self.connection_resource . finalize
## Returns the list of databases (or catalogs) for the connection.
databases : [Text]
databases =
databases self =
wrap_sql_errors <|
self.connection_resource.with connection->
metadata = connection.getMetaData
@ -68,7 +68,7 @@ type Connection
## Returns the list of schemas for the connection within the current database (or catalog).
schemas : [Text]
schemas =
schemas self =
wrap_sql_errors <|
self.connection_resource.with connection->
metadata = connection.getMetaData
@ -85,7 +85,7 @@ type Connection
- expected_types: an optional array of expected types of each column;
meant only for internal use.
execute_query : Text | Sql.Statement -> Vector Sql.Sql_Type -> Materialized_Table =
execute_query query expected_types=Nothing = handle_sql_errors <|
execute_query self query expected_types=Nothing = handle_sql_errors <|
self.with_prepared_statement query stmt->
rs = stmt.executeQuery
metadata = rs.getMetaData
@ -117,7 +117,7 @@ type Connection
- query: either raw SQL code as Text or an instance of Sql.Statement
representing the query to execute.
execute_update : Text | Sql.Statement -> Integer
execute_update query = handle_sql_errors <|
execute_update self query = handle_sql_errors <|
self.with_prepared_statement query stmt->
Panic.catch UnsupportedOperationException stmt.executeLargeUpdate _->
stmt.executeUpdate
@ -127,7 +127,7 @@ type Connection
Runs the provided action with a prepared statement, adding contextual
information to any thrown SQL errors.
with_prepared_statement : Text | Sql.Statement -> (PreparedStatement -> Any) -> Any
with_prepared_statement query action =
with_prepared_statement self query action =
prepare template holes = self.connection_resource . with java_connection->
stmt = java_connection.prepareStatement template
Panic.catch Any (set_statement_values stmt holes) caught_panic->
@ -154,7 +154,7 @@ type Connection
- table_name: The name of the table to fetch the column metadata for.
# fetch_columns : Text -> Vector [Text, Sql_Type]
fetch_columns : Text -> Vector Any
fetch_columns table_name =
fetch_columns self table_name =
query = IR.Select_All (IR.make_ctx_from table_name)
compiled = self.dialect.generate_sql query
self.with_prepared_statement compiled stmt->
@ -186,7 +186,7 @@ type Connection
- batch_size: Specifies how many rows should be uploaded in a single
batch.
upload_table : Text -> Materialized_Table -> Boolean -> Integer -> Database_Table
upload_table name table temporary=True batch_size=1000 = Panic.recover Illegal_State_Error <| handle_sql_errors <|
upload_table self name table temporary=True batch_size=1000 = Panic.recover Illegal_State_Error <| handle_sql_errors <|
column_types = table.columns.map col-> default_storage_type col.storage_type
column_names = table.columns.map .name
col_makers = column_names.zip column_types name-> typ->
@ -284,7 +284,7 @@ type Builder
- i: the index of the column to fetch from (starting from 1 as is the
ResultSet convention).
fetch_and_append : ResultSet -> Integer -> Nothing
fetch_and_append rs i = case self of
fetch_and_append self rs i = case self of
Builder_Inferred _ ->
obj = rs.getObject i
self.java_builder.append obj
@ -311,7 +311,7 @@ type Builder
Argument:
- name: The name of the column.
make_column : Text -> Java_Exports.Column
make_column name =
make_column self name =
storage = self.java_builder.seal
Java_Exports.make_column name storage
@ -325,7 +325,7 @@ type Unsupported_Dialect url
## Pretty print the error about unsupported SQL dialects.
Unsupported_Dialect.to_display_text : Text
Unsupported_Dialect.to_display_text =
Unsupported_Dialect.to_display_text self =
"Could not infer the SQL dialect for the database at " + self.url + "."
## PRIVATE
@ -373,7 +373,7 @@ type Sql_Error
Convert the SQL error to a textual representation.
to_text : Text
to_text =
to_text self =
query = if self.related_query.is_nothing.not then " [Query was: " + self.related_query + "]" else ""
"There was an SQL error: " + self.java_exception.getMessage.to_text + "." + query
@ -381,7 +381,7 @@ type Sql_Error
Pretty print the SQL error.
to_display_text : Text
to_display_text = self.to_text
to_display_text self = self.to_text
type Sql_Timeout_Error
@ -399,7 +399,7 @@ type Sql_Timeout_Error
Convert the timeout error to a textual representation.
to_text : Text
to_text =
to_text self =
query = if self.related_query.is_nothing.not then " [Query was: " + query + "]" else ""
"The SQL connection timed out: " + self.java_exception.getMessage + "." + query
@ -407,7 +407,7 @@ type Sql_Timeout_Error
Pretty print the timeout error.
to_display_text : Text
to_display_text = self.to_text
to_display_text self = self.to_text
## PRIVATE

View File

@ -6,5 +6,5 @@ type Connection_Options
## Merge the base set of options with the overrides in this object.
merge : Vector -> Vector
merge base_options =
merge self base_options =
base_options.filter x->(self.options.any (y->y.first==x.first) . not) + self.options

View File

@ -6,4 +6,4 @@ type Credentials
## Override `to_text` to mask the password field.
to_text : Text
to_text = 'Credentials ' + self.username + ' *****'
to_text self = 'Credentials ' + self.username + ' *****'

View File

@ -30,7 +30,7 @@ type Postgres
Arguments:
- options: Overrides for the connection properties.
connect : Connection_Options
connect options =
connect self options =
if Driver.isRegistered.not then Driver.register
properties = options.merge self.jdbc_properties
@ -38,12 +38,12 @@ type Postgres
## Provides the jdbc url for the connection.
jdbc_url : Text
jdbc_url =
jdbc_url self =
'jdbc:postgresql://' + self.host + ':' + self.port.to_text + (if self.database == '' then '' else '/' + self.database)
## Provides the properties for the connection.
jdbc_properties : [Pair Text Text]
jdbc_properties =
jdbc_properties self =
credentials = case self.credentials of
Nothing ->
env_user = Environment.get "PGUSER"
@ -69,7 +69,7 @@ type Postgres
## Provides the dialect needed for creating SQL statements.
dialect : Dialect
dialect = Dialect.postgres
dialect self = Dialect.postgres
## PRIVATE
Given an `SSL_Mode`, create the JDBC properties to secure a Postgres-based

View File

@ -30,7 +30,7 @@ type Redshift
Arguments:
- options: Overrides for the connection properties.
connect : Connection_Options
connect options =
connect self options =
if Driver.isRegistered.not then Driver.register
properties = options.merge self.jdbc_properties
@ -41,7 +41,7 @@ type Redshift
## Provides the jdbc url for the connection.
jdbc_url : Text
jdbc_url =
jdbc_url self =
prefix = case self.credentials of
AWS_Profile _ _ -> 'jdbc:redshift:iam://'
AWS_Key _ _ _ -> 'jdbc:redshift:iam://'
@ -50,7 +50,7 @@ type Redshift
## Provides the properties for the connection.
jdbc_properties : [Pair Text Text]
jdbc_properties =
jdbc_properties self =
credentials = case self.credentials of
Nothing -> Pgpass.read self.host self.port self.schema
AWS_Profile db_user profile ->
@ -70,7 +70,7 @@ type Redshift
## Provides the dialect needed for creating SQL statements.
dialect : Dialect
dialect = Dialect.redshift
dialect self = Dialect.redshift
type AWS_Profile
## Access Redshift using IAM via an AWS profile.

View File

@ -10,23 +10,23 @@ type SQLite
## Build the Connection resource.
connect : Connection_Options
connect options =
connect self options =
properties = options.merge self.jdbc_properties
Connection.create_jdbc_connection self.jdbc_url properties self.dialect
## Provides the jdbc url for the connection.
jdbc_url : Text
jdbc_url = case self.location of
jdbc_url self = case self.location of
In_Memory -> "jdbc:sqlite::memory:"
_ -> "jdbc:sqlite:" + ((File.new self.location).absolute.path.replace '\\' '/')
## Provides the properties for the connection.
jdbc_properties : Vector
jdbc_properties = []
jdbc_properties self = []
## Provides the dialect needed for creating SQL statements.
dialect : Dialect
dialect = Dialect.sqlite
dialect self = Dialect.sqlite
## Connect to an in-memory SQLite database.
type In_Memory

View File

@ -43,7 +43,7 @@ type Column
- show_rows: the number of initial rows that should be displayed.
- format_terminal: whether ANSI-terminal formatting should be used
display : Integer -> Boolean -> Text
display show_rows=10 format_terminal=False =
display self show_rows=10 format_terminal=False =
self.to_table.display show_rows format_terminal
## UNSTABLE
@ -53,7 +53,7 @@ type Column
Arguments:
- show_rows: the number of initial rows that should be displayed.
print : Nothing
print show_rows=10 =
print self show_rows=10 =
IO.println (self.display show_rows format_terminal=True)
IO.println ''
@ -61,13 +61,13 @@ type Column
Converts this column to JSON.
to_json : Json
to_json = self.to_sql.to_json
to_json self = self.to_sql.to_json
## UNSTABLE
Converts this column into a single-column table.
to_table : Table.Table
to_table =
to_table self =
Table.Table self.name self.connection [self.as_internal] self.context
## UNSTABLE
@ -78,7 +78,7 @@ type Column
- max_rows: specifies a maximum amount of rows to fetch; if not set, all
available rows are fetched.
to_dataframe : (Nothing | Integer) -> Materialized_Column.Column
to_dataframe max_rows=Nothing =
to_dataframe self max_rows=Nothing =
df = self.to_table.to_dataframe max_rows
df.at self.name
@ -86,7 +86,7 @@ type Column
Returns a vector containing all the elements in this column.
to_vector : Vector Any
to_vector =
to_vector self =
## We remove the index to avoid fetching index data that will not be
used anyway when constructing the raw Vector.
without_ix = self.to_table.set_index []
@ -98,7 +98,7 @@ type Column
Returns an Sql statement that will be used for materializing this column.
to_sql : Sql.Statement
to_sql = self.to_table.to_sql
to_sql self = self.to_table.to_sql
## PRIVATE
@ -115,7 +115,7 @@ type Column
`operand_type` is only relevant if the operand is not a column, it
defaults to the current type if not provided.
make_binary_op : Text -> Text -> (Column | Any) -> (Sql_Type | Nothing) -> (Sql_Type | Nothing) -> Column
make_binary_op op_kind operand new_type=Nothing operand_type=Nothing =
make_binary_op self op_kind operand new_type=Nothing operand_type=Nothing =
actual_new_type = new_type.if_nothing self.sql_type
case operand of
Column _ _ _ other_expr _ ->
@ -140,7 +140,7 @@ type Column
- new_type: The type of the SQL column that results from applying the
operator.
make_unary_op : Text -> Text -> (Sql_Type | Nothing) -> Column
make_unary_op op_kind new_type=Nothing =
make_unary_op self op_kind new_type=Nothing =
actual_new_type = new_type.if_nothing self.sql_type
new_expr = IR.Operation op_kind [self.expression]
Column self.name self.connection actual_new_type new_expr self.context
@ -165,32 +165,32 @@ type Column
`other` with matching indexes. If the index in `other` is not unique,
the corresponding rows of `self` will be duplicated in the result.
join : Table | Column -> Nothing | Text | Column | Vector (Text | Column) -> Boolean -> Text -> Text -> Table
join other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' =
join self other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' =
self.to_table.join other on drop_unmatched left_suffix right_suffix
## UNSTABLE
Sums the values in this column.
sum : Any
sum = self.compute_aggregate "SUM"
sum self = self.compute_aggregate "SUM"
## UNSTABLE
Computes the maximum element of this column.
max : Any
max = self.compute_aggregate "MAX"
max self = self.compute_aggregate "MAX"
## UNSTABLE
Computes the minimum element of this column.
min : Any
min = self.compute_aggregate "MIN"
min self = self.compute_aggregate "MIN"
## UNSTABLE
Computes the mean of non-missing elements of this column.
mean : Any
mean = self.compute_aggregate "AVG"
mean self = self.compute_aggregate "AVG"
## PRIVATE
@ -199,7 +199,7 @@ type Column
Arguments:
- op_name: The name of the operator to compute.
compute_aggregate : Text
compute_aggregate op_name =
compute_aggregate self op_name =
agg = make_aggregate self op_name
agg.to_vector . at 0
@ -207,19 +207,19 @@ type Column
Returns the length of this column.
length : Integer
length = self.to_table.row_count
length self = self.to_table.row_count
## UNSTABLE
Returns the number of missing items in this column.
count_missing : Integer
count_missing = self.where self.is_missing . length
count_missing self = self.where self.is_missing . length
## UNSTABLE
Returns the number of non-null items in this column.
count : Integer
count = self.where self.is_missing.not . length
count self = self.where self.is_missing.not . length
## UNSTABLE
@ -232,7 +232,7 @@ type Column
`other`. If `other` is a column, the comparison is performed pairwise
between corresponding elements of `self` and `other`.
== : Column | Any -> Column
== other = self.make_binary_op "=" other new_type=Sql_Type.boolean
== self other = self.make_binary_op "=" other new_type=Sql_Type.boolean
## UNSTABLE
@ -245,7 +245,7 @@ type Column
`other`. If `other` is a column, the comparison is performed pairwise
between corresponding elements of `self` and `other`.
!= : Column | Any -> Column
!= other = self.make_binary_op "!=" other new_type=Sql_Type.boolean
!= self other = self.make_binary_op "!=" other new_type=Sql_Type.boolean
## UNSTABLE
@ -258,7 +258,7 @@ type Column
`other`. If `other` is a column, the comparison is performed pairwise
between corresponding elements of `self` and `other`.
>= : Column | Any -> Column
>= other = self.make_binary_op ">=" other new_type=Sql_Type.boolean
>= self other = self.make_binary_op ">=" other new_type=Sql_Type.boolean
## UNSTABLE
@ -271,7 +271,7 @@ type Column
`other`. If `other` is a column, the comparison is performed pairwise
between corresponding elements of `self` and `other`.
<= : Column | Any -> Column
<= other = self.make_binary_op "<=" other new_type=Sql_Type.boolean
<= self other = self.make_binary_op "<=" other new_type=Sql_Type.boolean
## UNSTABLE
@ -284,7 +284,7 @@ type Column
`other`. If `other` is a column, the comparison is performed pairwise
between corresponding elements of `self` and `other`.
> : Column | Any -> Column
> other = self.make_binary_op ">" other new_type=Sql_Type.boolean
> self other = self.make_binary_op ">" other new_type=Sql_Type.boolean
## UNSTABLE
@ -297,7 +297,7 @@ type Column
`other`. If `other` is a column, the comparison is performed pairwise
between corresponding elements of `self` and `other`.
< : Column | Any -> Column
< other = self.make_binary_op "<" other new_type=Sql_Type.boolean
< self other = self.make_binary_op "<" other new_type=Sql_Type.boolean
## UNSTABLE
@ -310,7 +310,7 @@ type Column
of `self`. If `other` is a column, the operation is performed pairwise
between corresponding elements of `self` and `other`.
+ : Column | Any -> Column
+ other = self.make_binary_op "+" other
+ self other = self.make_binary_op "+" other
## UNSTABLE
@ -323,7 +323,7 @@ type Column
element of `self`. If `other` is a column, the operation is performed
pairwise between corresponding elements of `self` and `other`.
- : Column | Any -> Column
- other = self.make_binary_op "-" other
- self other = self.make_binary_op "-" other
## UNSTABLE
@ -336,7 +336,7 @@ type Column
element of `self`. If `other` is a column, the operation is performed
pairwise between corresponding elements of `self` and `other`.
* : Column | Any -> Column
* other = self.make_binary_op "*" other
* self other = self.make_binary_op "*" other
## UNSTABLE
@ -349,7 +349,7 @@ type Column
by `other`. If `other` is a column, the operation is performed pairwise
between corresponding elements of `self` and `other`.
/ : Column | Any -> Column
/ other = self.make_binary_op "/" other
/ self other = self.make_binary_op "/" other
## UNSTABLE
@ -363,7 +363,7 @@ type Column
operation is performed pairwise between corresponding elements of `self`
and `other`.
&& : Column | Any -> Column
&& other = self.make_binary_op "AND" other
&& self other = self.make_binary_op "AND" other
## UNSTABLE
@ -377,27 +377,27 @@ type Column
operation is performed pairwise between corresponding elements of `self`
and `other`.
|| : Column | Any -> Column
|| other = self.make_binary_op "OR" other
|| self other = self.make_binary_op "OR" other
## UNSTABLE
Boolean negation of each element in this column.
not : Column
not = self.make_unary_op "NOT"
not self = self.make_unary_op "NOT"
## UNSTABLE
Returns a column of booleans, with `True` items at the positions where
this column contains a `Nothing`.
is_missing : Column
is_missing = self.make_unary_op "ISNULL" new_type=Sql_Type.boolean
is_missing self = self.make_unary_op "ISNULL" new_type=Sql_Type.boolean
## UNSTABLE
Returns a new column where missing values have been replaced with the
provided default.
fill_missing : Any -> Column
fill_missing default = self.make_binary_op "FILLNULL" default
fill_missing self default = self.make_binary_op "FILLNULL" default
## UNSTABLE
@ -414,7 +414,7 @@ type Column
has the value `"Valid"`
my_column.where (status_column == "Valid")
where : Column -> Column
where filter =
where self filter =
case Helpers.check_integrity self filter of
False ->
Error.throw (Integrity_Error "Column "+filter.name)
@ -427,7 +427,7 @@ type Column
Returns a new column without rows that had missing values.
drop_missing : Any -> Column
drop_missing = self.where self.is_missing.not
drop_missing self = self.where self.is_missing.not
## UNSTABLE
@ -436,7 +436,7 @@ type Column
Arguments:
- new_name: The name to rename `self` column to.
rename : Text -> Column
rename new_name = case Helpers.ensure_name_is_sane new_name of
rename self new_name = case Helpers.ensure_name_is_sane new_name of
True ->
is_used_in_index = self.context.meta_index.exists i-> i.name == new_name
case is_used_in_index of
@ -463,7 +463,7 @@ type Column
Sorting `column` in descending order.
column.sort order=Sort_Direction.Descending
sort : Sort_Direction -> Column
sort order=Sort_Direction.Ascending =
sort self order=Sort_Direction.Ascending =
self.to_table.order_by (Sort_Column_Selector.By_Column [Sort_Column.Column self order]) . at self.name
## UNSTABLE
@ -478,7 +478,7 @@ type Column
missing value (a Nothing or a column with missing values), the behaviour
on these missing values is vendor specific.
starts_with : Column | Text -> Column
starts_with other = self.make_binary_op "starts_with" other new_type=Sql_Type.boolean
starts_with self other = self.make_binary_op "starts_with" other new_type=Sql_Type.boolean
## UNSTABLE
@ -492,7 +492,7 @@ type Column
missing value (a Nothing or a column with missing values), the behaviour
on these missing values is vendor specific.
ends_with : Column | Text -> Column
ends_with other = self.make_binary_op "ends_with" other new_type=Sql_Type.boolean
ends_with self other = self.make_binary_op "ends_with" other new_type=Sql_Type.boolean
## UNSTABLE
@ -506,11 +506,11 @@ type Column
missing value (a Nothing or a column with missing values), the behaviour
on these missing values is vendor specific.
contains : Column | Text -> Column
contains other = self.make_binary_op "contains" other new_type=Sql_Type.boolean
contains self other = self.make_binary_op "contains" other new_type=Sql_Type.boolean
## PRIVATE
as_internal : IR.Internal_Column
as_internal = IR.Internal_Column self.name self.sql_type self.expression
as_internal self = IR.Internal_Column self.name self.sql_type self.expression
type Aggregate_Column_Builder
@ -539,7 +539,7 @@ type Aggregate_Column_Builder
- name_suffix: a suffix that will be appended to the original column name
to generate the resulting column name.
sum : Text -> Column
sum name_suffix='_sum' =
sum self name_suffix='_sum' =
make_aggregate self "SUM" name_suffix
## UNSTABLE
@ -550,7 +550,7 @@ type Aggregate_Column_Builder
- name_suffix: a suffix that will be appended to the original column name
to generate the resulting column name.
max : Text -> Column
max name_suffix='_max' =
max self name_suffix='_max' =
make_aggregate self "MAX" name_suffix
## UNSTABLE
@ -561,7 +561,7 @@ type Aggregate_Column_Builder
- name_suffix: a suffix that will be appended to the original column name
to generate the resulting column name.
min : Text -> Column
min name_suffix='_min' =
min self name_suffix='_min' =
make_aggregate self "MIN" name_suffix
## UNSTABLE
@ -572,7 +572,7 @@ type Aggregate_Column_Builder
- name_suffix: a suffix that will be appended to the original column name
to generate the resulting column name.
count : Text -> Column
count name_suffix='_count' =
count self name_suffix='_count' =
make_aggregate self "COUNT" name_suffix new_type=Sql_Type.integer
## UNSTABLE
@ -583,14 +583,14 @@ type Aggregate_Column_Builder
- name_suffix: a suffix that will be appended to the original column name
to generate the resulting column name.
mean : Text -> Column
mean name_suffix='_mean' =
mean self name_suffix='_mean' =
make_aggregate self "AVG" name_suffix
## PRIVATE
A helper that returns the underlying column from before grouping.
ungrouped : Column
ungrouped =
ungrouped self =
new_ctx = self.context.set_groups []
Column self.name self.connection self.sql_type self.expression new_ctx

View File

@ -23,14 +23,14 @@ type Dialect
## PRIVATE
Name of the dialect.
name : Text
name = Errors.unimplemented "This is an interface only."
name self = Errors.unimplemented "This is an interface only."
## PRIVATE
A function which generates SQL code from the internal representation
according to the specific dialect.
generate_sql : Query -> Sql.Statement
generate_sql = Errors.unimplemented "This is an interface only."
generate_sql self = Errors.unimplemented "This is an interface only."
## PRIVATE
Deduces the result type for an aggregation operation.
@ -38,7 +38,7 @@ type Dialect
The provided aggregate is assumed to contain only already resolved columns.
You may need to transform it with `resolve_aggregate` first.
resolve_target_sql_type : Aggregate_Column -> Sql_Type
resolve_target_sql_type = Errors.unimplemented "This is an interface only."
resolve_target_sql_type self = Errors.unimplemented "This is an interface only."
## PRIVATE
Prepares an ordering descriptor.
@ -46,7 +46,7 @@ type Dialect
One of the purposes of this method is to verify if the expected ordering
settings are supported by the given database backend.
prepare_order_descriptor : IR.Internal_Column -> Sort_Direction -> Text_Ordering -> IR.Order_Descriptor
prepare_order_descriptor = Errors.unimplemented "This is an interface only."
prepare_order_descriptor self = Errors.unimplemented "This is an interface only."
## PRIVATE

View File

@ -29,13 +29,13 @@ type Postgres_Dialect
## PRIVATE
Name of the dialect.
name : Text
name = "PostgreSQL"
name self = "PostgreSQL"
## PRIVATE
A function which generates SQL code from the internal representation
according to the specific dialect.
generate_sql : Query -> Sql.Statement
generate_sql query =
generate_sql self query =
Base_Generator.generate_query self.internal_generator_dialect query . build
## PRIVATE
@ -44,7 +44,7 @@ type Postgres_Dialect
The provided aggregate is assumed to contain only already resolved columns.
You may need to transform it with `resolve_aggregate` first.
resolve_target_sql_type : Aggregate_Column -> Sql_Type
resolve_target_sql_type aggregate = resolve_target_sql_type aggregate
resolve_target_sql_type self aggregate = resolve_target_sql_type aggregate
## PRIVATE
Prepares an ordering descriptor.
@ -52,7 +52,7 @@ type Postgres_Dialect
One of the purposes of this method is to verify if the expected ordering
settings are supported by the given database backend.
prepare_order_descriptor : IR.Internal_Column -> Sort_Direction -> Text_Ordering -> IR.Order_Descriptor
prepare_order_descriptor internal_column sort_direction text_ordering =
prepare_order_descriptor self internal_column sort_direction text_ordering =
make_order_descriptor internal_column sort_direction text_ordering
## PRIVATE

View File

@ -26,13 +26,13 @@ type Redshift_Dialect
## PRIVATE
Name of the dialect.
name : Text
name = "redshift"
name self = "redshift"
## PRIVATE
A function which generates SQL code from the internal representation
according to the specific dialect.
generate_sql : Query -> Sql.Statement
generate_sql query =
generate_sql self query =
Base_Generator.generate_query self.internal_generator_dialect query . build
## PRIVATE
@ -41,7 +41,7 @@ type Redshift_Dialect
The provided aggregate is assumed to contain only already resolved columns.
You may need to transform it with `resolve_aggregate` first.
resolve_target_sql_type : Aggregate_Column -> Sql_Type
resolve_target_sql_type aggregate =
resolve_target_sql_type self aggregate =
Postgres.resolve_target_sql_type aggregate
## PRIVATE
@ -50,5 +50,5 @@ type Redshift_Dialect
One of the purposes of this method is to verify if the expected ordering
settings are supported by the given database backend.
prepare_order_descriptor : IR.Internal_Column -> Sort_Direction -> Text_Ordering -> IR.Order_Descriptor
prepare_order_descriptor internal_column sort_direction text_ordering =
prepare_order_descriptor self internal_column sort_direction text_ordering =
Postgres.make_order_descriptor internal_column sort_direction text_ordering

View File

@ -27,13 +27,13 @@ type SQLite_Dialect
## PRIVATE
Name of the dialect.
name : Text
name = "SQLite"
name self = "SQLite"
## PRIVATE
A function which generates SQL code from the internal representation
according to the specific dialect.
generate_sql : Query -> Sql.Statement
generate_sql query =
generate_sql self query =
Base_Generator.generate_query self.internal_generator_dialect query . build
## PRIVATE
@ -42,7 +42,7 @@ type SQLite_Dialect
The provided aggregate is assumed to contain only already resolved columns.
You may need to transform it with `resolve_aggregate` first.
resolve_target_sql_type : Aggregate_Column -> Sql_Type
resolve_target_sql_type aggregate = resolve_target_sql_type aggregate
resolve_target_sql_type self aggregate = resolve_target_sql_type aggregate
## PRIVATE
Prepares an ordering descriptor.
@ -50,7 +50,7 @@ type SQLite_Dialect
One of the purposes of this method is to verify if the expected ordering
settings are supported by the given database backend.
prepare_order_descriptor : IR.Internal_Column -> Sort_Direction -> Text_Ordering -> IR.Order_Descriptor
prepare_order_descriptor internal_column sort_direction text_ordering = case internal_column.sql_type.is_likely_text of
prepare_order_descriptor self internal_column sort_direction text_ordering = case internal_column.sql_type.is_likely_text of
True ->
if text_ordering.sort_digits_as_numbers then Error.throw (Unsupported_Database_Operation_Error "Natural ordering is not supported by the SQLite backend. You may need to materialize the Table to perform this operation.") else
case text_ordering.case_sensitive of

View File

@ -33,7 +33,7 @@ type Internal_Dialect
# extend_with : Vector [Text, Vector Sql.Builder -> Sql.Builder] -> Internal_Dialect
extend_with : Vector Any -> Internal_Dialect
extend_with mappings =
extend_with self mappings =
new_map = mappings.fold self.operation_map (m -> el -> m.insert (el.at 0) (el.at 1))
Internal_Dialect new_map self.wrap_identifier

View File

@ -52,7 +52,7 @@ type Unsupported_Name_Error text
Creates a human-readable representation of the unsupported name error.
Unsupported_Name_Error.to_display_text : Text
Unsupported_Name_Error.to_display_text =
Unsupported_Name_Error.to_display_text self =
"The name " + self.text + " is not currently supported by the Database library."
## PRIVATE

View File

@ -62,7 +62,7 @@ type Internal_Column
Arguments:
- new_name: The new name for the column.
rename : Text -> Internal_Column
rename new_name = Internal_Column new_name self.sql_type self.expression
rename self new_name = Internal_Column new_name self.sql_type self.expression
## PRIVATE
@ -100,7 +100,7 @@ type Context
Arguments:
- new_index: The new index to set in the query.
set_index : Vector Internal_Column -> Context
set_index new_index =
set_index self new_index =
Context self.from_spec self.where_filters self.orders self.groups new_index self.limit
## PRIVATE
@ -110,7 +110,7 @@ type Context
Arguments:
- new_filters: The new filters to set in the query.
set_where_filters : Vector Expression -> Context
set_where_filters new_filters =
set_where_filters self new_filters =
Context self.from_spec new_filters self.orders self.groups self.meta_index self.limit
## PRIVATE
@ -120,7 +120,7 @@ type Context
Arguments:
- new_orders: The new ordering clauses to set in the query.
set_orders : Vector Order_Descriptor -> Context
set_orders new_orders =
set_orders self new_orders =
Context self.from_spec self.where_filters new_orders self.groups self.meta_index self.limit
## PRIVATE
@ -137,7 +137,7 @@ type Context
Arguments:
- new_orders: The new ordering clauses to add to the query.
add_orders : Vector Order_Descriptor -> Context
add_orders new_orders =
add_orders self new_orders =
Context self.from_spec self.where_filters new_orders+self.orders self.groups self.meta_index self.limit
## PRIVATE
@ -147,7 +147,7 @@ type Context
Arguments:
- new_groups: The new grouping clauses to set in the query.
set_groups : Vector Expression -> Context
set_groups new_groups =
set_groups self new_groups =
Context self.from_spec self.where_filters self.orders new_groups self.meta_index self.limit
## PRIVATE
@ -157,7 +157,7 @@ type Context
Arguments:
- new_limit: The new limit clauses to set in the query.
set_limit : (Nothing | Integer) -> Context
set_limit new_limit =
set_limit self new_limit =
Context self.from_spec self.where_filters self.orders self.groups self.meta_index new_limit
## PRIVATE
@ -176,7 +176,7 @@ type Context
This is useful as a preprocessing step between combining queries, for example in a join.
# as_subquery : Text -> Vector (Vector Internal_Column) -> [IR.Sub_Query, Vector (Vector Internal_Column)]
as_subquery : Text -> Vector Any -> Vector
as_subquery alias column_lists =
as_subquery self alias column_lists =
rewrite_internal_column : Internal_Column -> Internal_Column
rewrite_internal_column column =
Internal_Column column.name column.sql_type (IR.Column alias column.name)

View File

@ -59,7 +59,7 @@ type Sql_Type
- name: a database-specific type name, used for pretty printing.
type Sql_Type typeid name
== that = case that of
== self that = case that of
Sql_Type that_id _ ->
self.typeid == that_id
_ -> False
@ -118,7 +118,7 @@ type Sql_Type
It only handles the standard types so it may return false negatives for
non-standard ones.
is_definitely_integer : Boolean
is_definitely_integer =
is_definitely_integer self =
[Types.INTEGER, Types.BIGINT, Types.SMALLINT, Types.TINYINT].contains self.typeid
## PRIVATE
@ -128,7 +128,7 @@ type Sql_Type
It only handles the standard types so it may return false negatives for
non-standard ones.
is_definitely_boolean : Boolean
is_definitely_boolean =
is_definitely_boolean self =
[Types.BOOLEAN, Types.BIT].contains self.typeid
## PRIVATE
@ -138,20 +138,20 @@ type Sql_Type
It only handles the standard types so it may return false negatives for
non-standard ones.
is_definitely_double : Boolean
is_definitely_double =
is_definitely_double self =
[Types.FLOAT, Types.DOUBLE, Types.REAL].contains self.typeid
## PRIVATE
Returns True if this type represents a Text.
is_definitely_text : Boolean
is_definitely_text =
is_definitely_text self =
[Types.VARCHAR, Types.LONGVARCHAR, Types.NVARCHAR, Types.LONGNVARCHAR].contains self.typeid
## PRIVATE
Returns True if this type represents a Text, using heuristics that may
match more possible types.
is_likely_text : Boolean
is_likely_text =
is_likely_text self =
self.is_definitely_text || self.name.contains "text" (Text_Matcher Case_Insensitive)
@ -208,7 +208,7 @@ type Statement
- Sql_Interpolation, representing objects that will be interpolated in
between the SQL code.
fragments : Vector Sql_Fragment
fragments = self.internal_fragments
fragments self = self.internal_fragments
## UNSAFE
UNSTABLE
@ -223,7 +223,7 @@ type Statement
It should NEVER be used in production code.
unsafe_to_raw_sql : Text
unsafe_to_raw_sql =
unsafe_to_raw_sql self =
strings = self.internal_fragments . map <| case _ of
Sql_Code_Part code -> code
# TODO at some point we may try more sophisticated serialization based on data type
@ -237,7 +237,7 @@ type Statement
Returns a pair consisting of the SQL code with holes for values and
a list for values that should be substituted.
# prepare : [Text, Vector Any]
prepare =
prepare self =
to_code fragment = case fragment of
Sql_Code_Part code -> code
Sql_Interpolation _ _ -> "?"
@ -252,7 +252,7 @@ type Statement
Returns a JSON representation of the statement.
to_json : Json
to_json =
to_json self =
jsonify fragment = case fragment of
Sql_Code_Part code -> Json.from_pairs [["sql_code", code]]
Sql_Interpolation typ obj ->
@ -282,19 +282,19 @@ type Builder
Arguments:
- other: The code fragment to append to `self`.
++ : Builder -> Builder
++ other = Builder (self.fragments ++ other.fragments)
++ self other = Builder (self.fragments ++ other.fragments)
## UNSTABLE
Checks if the builder represents an empty code fragment.
is_empty : Boolean
is_empty = self.fragments.is_empty
is_empty self = self.fragments.is_empty
## UNSTABLE
Builds a SQL statement.
build : Statement
build =
build self =
fragments = optimize_fragments self.fragments.build
Statement fragments
@ -302,7 +302,7 @@ type Builder
Wraps the code fragment in parentheses.
paren : Builder
paren =
paren self =
l = code "("
r = code ")"
l ++ self ++ r
@ -316,7 +316,7 @@ type Builder
Empty fragments are unaffected.
prefix_if_present : Text | Builder -> Builder
prefix_if_present prefix =
prefix_if_present self prefix =
pref = case prefix of
Builder _ -> prefix
_ -> code prefix

View File

@ -55,7 +55,7 @@ type Table
- show_rows: the number of initial rows that should be displayed.
- format_terminal: whether ANSI-terminal formatting should be used
display : Integer -> Boolean -> Text
display show_rows=10 format_terminal=False =
display self show_rows=10 format_terminal=False =
df = self.reset_index.to_dataframe max_rows=show_rows
indices_count = self.context.meta_index.length
all_rows_count = self.row_count
@ -68,7 +68,7 @@ type Table
Arguments:
- show_rows: the number of initial rows that should be displayed.
print : Integer -> Nothing
print show_rows=10 =
print self show_rows=10 =
IO.println (self.display show_rows format_terminal=True)
IO.println ''
@ -76,7 +76,7 @@ type Table
Converts this table into a JSON structure.
to_json : Json
to_json = case self.internal_columns.is_empty of
to_json self = case self.internal_columns.is_empty of
True ->
Json.from_pairs [["query", Nothing], ["message", "The table has no columns so a query cannot be generated."]]
False -> self.to_sql.to_json
@ -88,7 +88,7 @@ type Table
Arguments:
- name: The name of the column to get.
at : Text -> Column ! No_Such_Column_Error
at name =
at self name =
candidates = self.internal_columns + self.context.meta_index
internal = candidates.find (p -> p.name == name)
self.make_column internal . map_error (_ -> No_Such_Column_Error name)
@ -141,7 +141,7 @@ type Table
table.select_columns (By_Column [column1, column2])
select_columns : Column_Selector -> Boolean -> Problem_Behavior -> Table
select_columns (columns = By_Index [0]) (reorder = False) (on_problems = Report_Warning) =
select_columns self (columns = By_Index [0]) (reorder = False) (on_problems = Report_Warning) =
new_columns = Table_Helpers.select_columns internal_columns=self.internal_columns selector=columns reorder=reorder on_problems=on_problems
self.updated_columns new_columns
@ -190,7 +190,7 @@ type Table
table.remove_columns (By_Column [column1, column2])
remove_columns : Column_Selector -> Problem_Behavior -> Table
remove_columns (columns = By_Index [0]) (on_problems = Report_Warning) =
remove_columns self (columns = By_Index [0]) (on_problems = Report_Warning) =
new_columns = Table_Helpers.remove_columns internal_columns=self.internal_columns selector=columns on_problems=on_problems
self.updated_columns new_columns
@ -244,7 +244,7 @@ type Table
table.reorder_columns (By_Column [column1, column2])
reorder_columns : Column_Selector -> Position.Position -> Problem_Behavior -> Table
reorder_columns (columns = By_Index [0]) (position = Position.Before_Other_Columns) (on_problems = Report_Warning) =
reorder_columns self (columns = By_Index [0]) (position = Position.Before_Other_Columns) (on_problems = Report_Warning) =
new_columns = Table_Helpers.reorder_columns internal_columns=self.internal_columns selector=columns position=position on_problems=on_problems
self.updated_columns new_columns
@ -271,7 +271,7 @@ type Table
table.reorder_columns Sort_Direction.Descending
sort_columns : Sort_Direction -> Text_Ordering -> Table
sort_columns direction=Sort_Direction.Ascending text_ordering=Text_Ordering =
sort_columns self direction=Sort_Direction.Ascending text_ordering=Text_Ordering =
new_columns = Table_Helpers.sort_columns internal_columns=self.internal_columns direction text_ordering
self.updated_columns new_columns
@ -299,7 +299,7 @@ type Table
> Example
rename_columns : Column_Name_Mapping -> Problem_Behavior -> Table
rename_columns (column_map=(Column_Name_Mapping.By_Position ["Column"])) (on_problems=Report_Warning) =
rename_columns self (column_map=(Column_Name_Mapping.By_Position ["Column"])) (on_problems=Report_Warning) =
new_names = Table_Helpers.rename_columns internal_columns=self.internal_columns mapping=column_map on_problems=on_problems
if new_names.is_error then new_names else
new_columns = self.internal_columns.map_with_index i->c->(c.rename (new_names.at i))
@ -315,7 +315,7 @@ type Table
If instead of a name, a column is provided, it is returned as-is as long
as it comes from the same context.
resolve : Text | Column -> Column
resolve column = case column of
resolve self column = case column of
Text -> Panic.rethrow (self.at column)
_ ->
if Helpers.check_integrity self column then column else
@ -337,7 +337,7 @@ type Table
value `"Valid"`
my_table.where (my_table.at "Status" == "Valid")
where : Column -> Table
where filter =
where self filter =
case Helpers.check_integrity self filter of
False ->
Error.throw (Integrity_Error "Column "+filter.name)
@ -377,7 +377,7 @@ type Table
t2 = t1.where (t1.at 'A' > 5)
t2.to_dataframe
limit : Integer -> Table
limit max_rows =
limit self max_rows =
new_ctx = self.context.set_limit max_rows
self.updated_context new_ctx
@ -392,7 +392,7 @@ type Table
If a column with the given name already exists, it will be replaced.
Otherwise a new column is added.
set : Text -> Column -> Table
set name column = case Helpers.ensure_name_is_sane name of
set self name column = case Helpers.ensure_name_is_sane name of
True ->
is_used_in_index = self.context.meta_index.exists i-> i.name == name
case is_used_in_index of
@ -411,7 +411,7 @@ type Table
Returns the vector of columns contained in this table.
columns : Vector Column
columns = self.internal_columns . map self.make_column
columns self = self.internal_columns . map self.make_column
## UNSTABLE
@ -420,7 +420,7 @@ type Table
Arguments:
- index: The column to use as the index of the table.
set_index : Text | Column | Vector Text -> Table
set_index index = Panic.recover Any <|
set_index self index = Panic.recover Any <|
new_index = (Helpers.unify_vector_singleton index).map (self.at >> .as_internal)
new_ctx = self.context.set_index new_index
new_cols = self.internal_columns.filter col->
@ -432,7 +432,7 @@ type Table
Returns the (possibly empty) list of indices for this table.
indices : Vector Column
indices =
indices self =
self.context.meta_index.map self.make_column
## UNSTABLE
@ -442,7 +442,7 @@ type Table
Throws `No_Index_Set_Error` if there is no index set.
index : Column | Vector Column ! Materialized_Table.No_Index_Set_Error
index =
index self =
ixes = self.indices
len = ixes.length
if len == 0 then Error.throw Materialized_Table.No_Index_Set_Error else
@ -504,7 +504,7 @@ type Table
table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name 'Quantity', Sort_Column.Name 'Rating' Sort_Direction.Descending])
order_by : Sort_Column_Selector -> Text_Ordering -> Problem_Behavior -> Table
order_by (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering on_problems=Report_Warning = Panic.handle_wrapped_dataflow_error <|
order_by self (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering on_problems=Report_Warning = Panic.handle_wrapped_dataflow_error <|
problem_builder = Problem_Builder.new
columns_for_ordering = Table_Helpers.prepare_order_by self.columns columns problem_builder
problem_builder.attach_problems_before on_problems <|
@ -539,7 +539,7 @@ type Table
`other` with matching indexes. If the index in `other` is not unique,
the corresponding rows of `self` will be duplicated in the result.
join : Table | Column -> Nothing | Text | Column | Vector (Text | Column) -> Boolean -> Text -> Text -> Table
join other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' = case other of
join self other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' = case other of
Column _ _ _ _ _ -> self.join other.to_table on drop_unmatched left_suffix right_suffix
Table _ _ _ _ -> Panic.recover Any <|
Panic.rethrow (Helpers.ensure_name_is_sane left_suffix && Helpers.ensure_name_is_sane right_suffix)
@ -638,7 +638,7 @@ type Table
table.aggregate [Group_By "Key", Count Nothing]
aggregate : [Aggregate_Column] -> Problem_Behavior -> Table
aggregate columns (on_problems=Report_Warning) =
aggregate self columns (on_problems=Report_Warning) =
validated = Aggregate_Column_Helper.prepare_aggregate_columns columns self
on_problems.attach_problems_before validated.problems <|
key_columns = validated.key_columns
@ -662,7 +662,7 @@ type Table
## Parsing values is not supported in database tables, the table has to be
materialized first with `to_dataframe`.
parse_values : Data_Formatter -> (Nothing | [Column_Type_Selection]) -> Problem_Behavior -> Table
parse_values value_formatter=Data_Formatter column_types=Nothing on_problems=Report_Warning =
parse_values self value_formatter=Data_Formatter column_types=Nothing on_problems=Report_Warning =
## Avoid unused arguments warning. We cannot rename arguments to `_`,
because we need to keep the API consistent with the in-memory table.
_ = [value_formatter, column_types, on_problems]
@ -674,7 +674,7 @@ type Table
Returns a new Table without rows that contained missing values in any of
the columns.
drop_missing_rows : Table
drop_missing_rows =
drop_missing_rows self =
filters = self.columns.map (c -> c.is_missing.not.expression)
new_ctx = self.context.set_where_filters (self.context.where_filters + filters)
self.updated_context new_ctx
@ -684,7 +684,7 @@ type Table
This operation needs to actually materialize the underlying query in
order to know which columns to drop.
drop_missing_columns : Table
drop_missing_columns =
drop_missing_columns self =
rows_expr = IR.Operation "COUNT_ROWS" []
all_rows_column_name = "row_count"
make_count_expr expr = IR.Operation "COUNT" [expr]
@ -699,7 +699,7 @@ type Table
## Returns the amount of rows in this table.
row_count : Integer
row_count = if self.internal_columns.is_empty then 0 else
row_count self = if self.internal_columns.is_empty then 0 else
expr = IR.Operation "COUNT_ROWS" []
column_name = "row_count"
## We need to keep some column in the subquery which will determine if
@ -721,7 +721,7 @@ type Table
- max_rows: specifies a maximum amount of rows to fetch; if not set, all
available rows are fetched.
to_dataframe : (Integer | Nothing) -> Materialized_Table.Table
to_dataframe max_rows=Nothing =
to_dataframe self max_rows=Nothing =
case self.context.meta_index.length > 1 of
True -> Error.throw <| Illegal_State_Error "Multi-indexes are not implemented in the dataframes, if you want to materialize such a Table, remove the index first using `set_index`."
False ->
@ -744,7 +744,7 @@ type Table
Brings the index back as columns.
reset_index : Table
reset_index =
reset_index self =
new_cols = self.internal_columns_with_index
new_ctx = self.context.set_index []
self.updated_context new_ctx . updated_columns new_cols
@ -753,7 +753,7 @@ type Table
Returns an SQL statement that will be used for materializing this table.
to_sql : Sql.Statement
to_sql =
to_sql self =
cols = self.internal_columns.map (c -> [c.name, c.expression])
case cols.is_empty of
True -> Error.throw <| Unsupported_Database_Operation_Error "Cannot generate SQL for a table with no columns."
@ -766,7 +766,7 @@ type Table
The table lists all columns, counts of non-null items and storage types
of each column.
info : Table
info =
info self =
cols = self.internal_columns
count_query =
## Performing a subquery is the most robust way to handle both
@ -791,7 +791,7 @@ type Table
Arguments:
- internal: The internal column to use for creating a column.
make_column : Internal_Column -> Column
make_column internal =
make_column self internal =
# TODO [RW] Many places assume that index names are distinct from column names, so when creating a column from
# index we need to ensure that the names do not collide. In the future we may consider trying to get rid of
# these distinctness assumptions, to avoid this renaming.
@ -806,7 +806,7 @@ type Table
Arguments:
- columns: The columns with which to update this table.
updated_columns : Vector Internal_Column -> Table
updated_columns internal_columns = Table self.name self.connection internal_columns self.context
updated_columns self internal_columns = Table self.name self.connection internal_columns self.context
## PRIVATE
@ -815,7 +815,7 @@ type Table
Arguments:
- ctx: The new context for this table.
updated_context : Context -> Table
updated_context ctx = Table self.name self.connection self.internal_columns ctx
updated_context self ctx = Table self.name self.connection self.internal_columns ctx
## PRIVATE
@ -825,14 +825,14 @@ type Table
- ctx: The new context for this table.
- internal_columns: The new columns to include in the table.
updated_context_and_columns : Context -> Vector Internal_Column -> Table
updated_context_and_columns ctx internal_columns = Table self.name self.connection internal_columns ctx
updated_context_and_columns self ctx internal_columns = Table self.name self.connection internal_columns ctx
## PRIVATE
Returns a vector that contains first the internal representations of all
indices and then all columns.
internal_columns_with_index : Vector Internal_Column
internal_columns_with_index =
internal_columns_with_index self =
self.context.meta_index + self.internal_columns
@ -847,7 +847,7 @@ type Table
be called on the Table if no operations modifying it have been performed
like modifying, removing or adding columns, filtering, grouping etc.
insert : Vector Any -> Nothing
insert values =
insert self values =
table_name = case self.context.from_spec of
IR.From_Table name _ -> name
_ -> Error.throw <| Illegal_State_Error "Inserting can only be performed on tables as returned by `access_table`, any further processing is not allowed."
@ -917,7 +917,7 @@ type Table
table = connection.access_table "Table"
table.write (enso_project.data / "example_csv_output.csv")
write : File|Text -> File_Format -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing ! Column_Mismatch | Illegal_Argument_Error | File_Not_Found | IO_Error
write path format=File_Format.Auto on_existing_file=Existing_File_Behavior.Backup match_columns=Match_Columns.By_Name on_problems=Report_Warning =
write self path format=File_Format.Auto on_existing_file=Existing_File_Behavior.Backup match_columns=Match_Columns.By_Name on_problems=Report_Warning =
# TODO This should ideally be done in a streaming manner, or at least respect the row limits.
self.to_dataframe.write path format on_existing_file match_columns on_problems
@ -933,10 +933,10 @@ type Integrity_Error
# Return a readable description of this error.
to_text : Text
to_text = self.object_description + " comes from a different context."
to_text self = self.object_description + " comes from a different context."
to_display_text : Text
to_display_text = self.to_text
to_display_text self = self.to_text
## PRIVATE

View File

@ -5,5 +5,5 @@ from Standard.Base import all
type Unsupported_Database_Operation_Error message
Unsupported_Database_Operation_Error.to_display_text : Text
Unsupported_Database_Operation_Error.to_display_text =
Unsupported_Database_Operation_Error.to_display_text self =
"Unsupported database operation: " + self.message

View File

@ -41,7 +41,7 @@ type Pgpass_Entry
## PRIVATE
matches : Text -> Text|Integer -> Text -> Text -> Boolean
matches host port database username=Nothing =
matches self host port database username=Nothing =
wildcard='*'
host_match = self.host==wildcard || self.host==host
port_match = self.port==wildcard ||

View File

@ -19,7 +19,7 @@ type Object_Type
Convert GeoJSON object type to Text.
to_text : Text
to_text = case self of
to_text self = case self of
Feature -> "Feature"
Feature_Collection -> "FeatureCollection"
@ -27,7 +27,7 @@ type Object_Type
Get the type field of a GeoJSON object.
Json.Object.get_type : Any
Json.Object.get_type = case self of
Json.Object.get_type self = case self of
Json.Object object ->
object.get_or_else "type" Nothing.to_json . unwrap
@ -35,7 +35,7 @@ Json.Object.get_type = case self of
Get key-value pairs of a Feature GeoJSON object.
Json.Object.get_feature_row : Map
Json.Object.get_feature_row =
Json.Object.get_feature_row self =
properties_row = self.get "properties" . get_properties_row
geometry_row = self.get "geometry" . get_geometry_row
geometry_row.fold_with_key properties_row acc-> k-> v->
@ -45,7 +45,7 @@ Json.Object.get_feature_row =
Get column key-value pairs of a feature's "properties" object.
Json.Object.get_properties_row : Map
Json.Object.get_properties_row = case self of
Json.Object.get_properties_row self = case self of
Json.Object properties -> properties.map p-> case p of
Json.Object _ -> Nothing.to_json
_ -> p
@ -54,7 +54,7 @@ Json.Object.get_properties_row = case self of
Get column key-value pairs of a feature's "geometry" object.
Json.Object.get_geometry_row : Map
Json.Object.get_geometry_row = case self of
Json.Object.get_geometry_row self = case self of
Json.Object fields ->
geometry_type = fields.get_or_else "type" Nothing
if geometry_type == "Point".to_json then self.get_point_row else Map.empty
@ -63,7 +63,7 @@ Json.Object.get_geometry_row = case self of
Get column key-value pairs of a "Point" geometry object.
Json.Object.get_point_row : Map
Json.Object.get_point_row =
Json.Object.get_point_row self =
fields = ["longitude", "latitude", "elevation"]
case self.get "coordinates" of
Json.Array coordinates ->

View File

@ -19,7 +19,7 @@ type Google_Api_Client
- app_name: the application name to use for making the API calls. This
will show up in access logs etc.
spreadsheets : Text -> Spreadsheets_Service
spreadsheets app_name='Enso' =
spreadsheets self app_name='Enso' =
service = Sheets.Builder.new self.http_transport self.json_factory self.credential . setApplicationName app_name . build
Spreadsheets_Service service
@ -36,7 +36,7 @@ type Spreadsheets_Service
- sheet_range: specifies the sheet and cell range to read, e.g.
`'Sheet1!A1:B7'`.
get_table : Text -> Text -> Table
get_table sheet_id sheet_range =
get_table self sheet_id sheet_range =
request = self.java_service.spreadsheets.values.get sheet_id sheet_range . setMajorDimension 'COLUMNS' . setValueRenderOption 'UNFORMATTED_VALUE'
response = request.execute
values = Vector.Vector response.getValues . map Vector.Vector

View File

@ -61,7 +61,7 @@ read location flags=[] =
Write the image with applying several flags.
Codecs.write path image [Codecs.Write_Jpeg_Quality 40, Codecs.Write_Jpeg_Progressive]
Image.Image.write : (Text | File) -> (Write_Flag | Vector) -> Nothing ! File.IO_Error
Image.Image.write location flags=[] =
Image.Image.write self location flags=[] =
path = case location of
File.File -> location.path
_ -> location

View File

@ -31,7 +31,7 @@ type Histogram
histo = Examples.image.histogram 0
histo.to_json
to_json : Json
to_json =
to_json self =
bins = Json.from_pairs [["bins", self.data]]
Json.from_pairs [["data", bins]]
@ -50,6 +50,6 @@ type Histogram
example_histogram = Examples.image.histogram 0
Image.Image.histogram : Integer -> Histogram
Image.Image.histogram channel =
Image.Image.histogram self channel =
hist = Java_Histogram.calculate self.opencv_mat channel
Histogram channel (Vector.Vector hist.get_data)

View File

@ -55,7 +55,7 @@ type Image
example_rows = Examples.image.rows
rows : Integer
rows = self.opencv_mat.rows
rows self = self.opencv_mat.rows
## UNSTABLE
@ -68,7 +68,7 @@ type Image
example_cols = Examples.image.columns
columns : Integer
columns = self.opencv_mat.cols
columns self = self.opencv_mat.cols
## UNSTABLE
@ -81,7 +81,7 @@ type Image
example_channels = Examples.image.channels
channels : Integer
channels = self.opencv_mat.channels
channels self = self.opencv_mat.channels
## UNSTABLE
@ -98,7 +98,7 @@ type Image
example_get = Examples.image.get 10 10
get : Integer -> Integer -> Vector ! Matrix.Index_Out_Of_Bounds_Error
get row column =
get self row column =
if (row < 0) || (row >= self.rows) then Error.throw (Matrix.Index_Out_Of_Bounds_Error self.rows self.columns row) else
if (column < 0) || (column >= self.columns) then Error.throw (Matrix.Index_Out_Of_Bounds_Error self.rows self.columns column) else
arr = Java_Image.get self.opencv_mat row column
@ -153,7 +153,7 @@ type Image
image = Examples.image
image + (Matrix.zeros rows=image.rows columns=image.columns channels=image.channels)
+ : (Number | Vector | Matrix) -> Image ! Matrix.Dimensions_Not_Equal
+ value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.add _ _ _)) . catch Any Internal.core_op_handler
+ self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.add _ _ _)) . catch Any Internal.core_op_handler
## UNSTABLE
@ -204,7 +204,7 @@ type Image
image = Examples.image
image - (Matrix.zeros rows=image.rows columns=image.columns channels=image.channels)
- : (Number | Vector | Matrix) -> Image ! Matrix.Dimensions_Not_Equal
- value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.subtract _ _ _)) . catch Any Internal.core_op_handler
- self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.subtract _ _ _)) . catch Any Internal.core_op_handler
## UNSTABLE
@ -255,7 +255,7 @@ type Image
image = Examples.image
image * (Matrix.ones rows=image.rows columns=image.columns channels=image.channels)
* : (Number | Vector | Matrix) -> Image ! Matrix.Dimensions_Not_Equal
* value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.multiply _ _ _)) . catch Any Internal.core_op_handler
* self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.multiply _ _ _)) . catch Any Internal.core_op_handler
## UNSTABLE
@ -306,7 +306,7 @@ type Image
image = Examples.image
image / (Matrix.ones rows=image.rows columns=image.columns channels=image.channels)
/ : (Number | Vector | Matrix) -> Image ! Matrix.Dimensions_Not_Equal
/ value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.divide _ _ _)) . catch Any Internal.core_op_handler
/ self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Image.divide _ _ _)) . catch Any Internal.core_op_handler
## UNSTABLE
@ -330,7 +330,7 @@ type Image
example_eq = Examples.image == Examples.image
== : Image -> Boolean
== that = Java_Image.is_equals self.opencv_mat that.opencv_mat
== self that = Java_Image.is_equals self.opencv_mat that.opencv_mat
## UNSTABLE
@ -343,7 +343,7 @@ type Image
example_to_vector = Examples.image.to_vector
to_vector : Vector
to_vector =
to_vector self =
arr = Java_Image.to_vector self.opencv_mat
Vector.Vector arr
@ -358,7 +358,7 @@ type Image
example_to_json = Examples.image.to_json
to_json : Json
to_json =
to_json self =
base64 = Java_Image.to_base64 self.opencv_mat
Json.from_pairs [["mediaType", "image/png"], ["base64", base64]]
@ -373,5 +373,5 @@ type Image
example_to_mat = Examples.image.to_matrix
to_matrix : Matrix
to_matrix = Matrix.from_vector self.to_vector self.rows self.channels
to_matrix self = Matrix.from_vector self.to_vector self.rows self.channels

View File

@ -107,7 +107,7 @@ type Matrix
example_rows = Examples.matrix.rows
rows : Integer
rows = self.opencv_mat.rows
rows self = self.opencv_mat.rows
## UNSTABLE
@ -120,7 +120,7 @@ type Matrix
example_columns = Examples.matrix.columns
columns : Integer
columns = self.opencv_mat.cols
columns self = self.opencv_mat.cols
## Return the number of matrix channels.
@ -131,7 +131,7 @@ type Matrix
example_channels = Examples.matrix.channels
channels : Integer
channels = self.opencv_mat.channels
channels self = self.opencv_mat.channels
## UNSTABLE
@ -148,7 +148,7 @@ type Matrix
example_get = Examples.matrix.get 0 0
get : Integer -> Integer -> Vector ! Index_Out_Of_Bounds_Error
get row column =
get self row column =
if (row < 0) || (row >= self.rows) then Error.throw (Index_Out_Of_Bounds_Error self.rows self.columns row) else
if (column < 0) || (column >= self.columns) then Error.throw (Index_Out_Of_Bounds_Error self.rows self.columns column) else
arr = Java_Matrix.get self.opencv_mat row column
@ -169,7 +169,7 @@ type Matrix
example_rewhsape = Matrix.from_vector [0, 0, 0] . reshape rows=3 channels=1
reshape : Integer -> Integer -> Matrix
reshape rows channels=Nothing =
reshape self rows channels=Nothing =
case channels of
Nothing -> Matrix (self.opencv_mat.reshape self.channels rows)
_ -> Matrix (self.opencv_mat.reshape channels rows)
@ -210,7 +210,7 @@ type Matrix
example_plus = Examples.matrix + Examples.matrix
+ : (Number | Vector | Matrix) -> Matrix ! Dimensions_Not_Equal
+ value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.add _ _ _)) . catch Internal.core_op_handler
+ self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.add _ _ _)) . catch Internal.core_op_handler
## UNSTABLE
@ -249,7 +249,7 @@ type Matrix
example_minus = Examples.matrix - Examples.matrix
- : (Number | Vector | Matrix) -> Matrix ! Dimensions_Not_Equal
- value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.subtract _ _ _)) . catch Internal.core_op_handler
- self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.subtract _ _ _)) . catch Internal.core_op_handler
## UNSTABLE
@ -293,7 +293,7 @@ type Matrix
Multiply two matrices.
m * m
* : (Number | Vector | Matrix) -> Matrix ! Dimensions_Not_Equal
* value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.multiply _ _ _)) . catch Internal.core_op_handler
* self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.multiply _ _ _)) . catch Internal.core_op_handler
## UNSTABLE
@ -331,7 +331,7 @@ type Matrix
example_div = Examples.matrix / Examples.matrix
/ : (Number | Vector | Matrix) -> Matrix ! Dimensions_Not_Equal
/ value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.divide _ _ _)) . catch Internal.core_op_handler
/ self value = Panic.recover Any (Internal.core_op self.opencv_mat value (Java_Matrix.divide _ _ _)) . catch Internal.core_op_handler
## UNSTABLE
@ -351,7 +351,7 @@ type Matrix
example_eq = Examples.matrix == Examples.matrix
== : Matrix -> Boolean
== that = Java_Matrix.is_equals self.opencv_mat that.opencv_mat
== self that = Java_Matrix.is_equals self.opencv_mat that.opencv_mat
## UNSTABLE
@ -384,7 +384,7 @@ type Matrix
example_normalize = Matrix.identity 3 3 . normalize
normalize : Number -> Number -> Matrix
normalize min_value=0.0 max_value=1.0 =
normalize self min_value=0.0 max_value=1.0 =
Matrix (Java_Matrix.normalize self.opencv_mat min_value max_value)
## UNSTABLE
@ -398,7 +398,7 @@ type Matrix
example_to_image = Examples.matrix.to_image
to_image : Image.Image
to_image = Image.Image (Image.from_vector self.normalize.to_vector self.rows self.channels)
to_image self = Image.Image (Image.from_vector self.normalize.to_vector self.rows self.channels)
## UNSTABLE
@ -411,7 +411,7 @@ type Matrix
example_to_vector = Examples.matrix.to_vector
to_vector : Vector
to_vector =
to_vector self =
arr = Java_Matrix.to_vector self.opencv_mat
Vector.Vector arr
@ -426,7 +426,7 @@ type Matrix
example_to_json = Examples.matrix.to_json
to_json : Json
to_json = Json.String self.opencv_mat.to_text
to_json self = Json.String self.opencv_mat.to_text
## UNSTABLE
type Matrix_Error
@ -451,7 +451,7 @@ type Matrix_Error
Pretty-prints a matrix error to be readable by the users.
to_display_text : Text
to_display_text = case self of
to_display_text self = case self of
Index_Out_Of_Bounds_Error rows columns index ->
'For a matrix with dimensions ' + rows.to_text + 'x' + columns.to_text + ', the index ' + index.to_text + ' is out of bounds.'
Dimensions_Not_Equal ->

View File

@ -46,7 +46,7 @@ type Column
example_display = Examples.integer_column.display
display : Integer -> Boolean -> Text
display show_rows=10 format_terminal=False =
display self show_rows=10 format_terminal=False =
java_col = self.java_column
index = java_col.getIndex
col_name = java_col.getName
@ -77,7 +77,7 @@ type Column
example_display = Examples.integer_column.print
print : Integer -> Nothing
print show_rows=10 =
print self show_rows=10 =
IO.println (self.display show_rows format_terminal=True)
IO.println ''
@ -105,7 +105,7 @@ type Column
example_eq = Examples.integer_column == 1
== : Column | Any -> Column
== other =
== self other =
run_vectorized_binary_op self "==" (==) other
## Element-wise non-equality comparison.
@ -132,7 +132,7 @@ type Column
example_neq = Examples.integer_column != 1
!= : Column | Any -> Column
!= other = (self == other).not
!= self other = (self == other).not
## Element-wise order comparison.
@ -158,7 +158,7 @@ type Column
example_geq = Examples.integer_column >= 1
>= : Column | Any -> Column
>= other =
>= self other =
run_vectorized_binary_op self ">=" (>=) other
## Element-wise order comparison.
@ -185,7 +185,7 @@ type Column
example_leq = Examples.integer_column <= 1
<= : Column | Any -> Column
<= other =
<= self other =
run_vectorized_binary_op self "<=" (<=) other
## Element-wise order comparison.
@ -212,7 +212,7 @@ type Column
example_gt = Examples.integer_column > 1
> : Column | Any -> Column
> other =
> self other =
run_vectorized_binary_op self ">" (>) other
## Element-wise order comparison.
@ -239,7 +239,7 @@ type Column
example_lt = Examples.integer_column < 1
< : Column | Any -> Column
< other = run_vectorized_binary_op self "<" (<) other
< self other = run_vectorized_binary_op self "<" (<) other
## ALIAS Add Columns
@ -267,7 +267,7 @@ type Column
example_plus = Examples.integer_column + 10
+ : Column | Any -> Column
+ other = run_vectorized_binary_op self '+' (+) other
+ self other = run_vectorized_binary_op self '+' (+) other
## ALIAS Subtract Columns
@ -295,7 +295,7 @@ type Column
example_minus = Examples.integer_column - 10
- : Column | Any -> Column
- other = run_vectorized_binary_op self '-' (-) other
- self other = run_vectorized_binary_op self '-' (-) other
## ALIAS Multiply Columns
@ -323,7 +323,7 @@ type Column
example_mul = Examples.integer_column * 10
* : Column | Any -> Column
* other = run_vectorized_binary_op self '*' (*) other
* self other = run_vectorized_binary_op self '*' (*) other
## ALIAS Divide Columns
@ -351,7 +351,7 @@ type Column
example_div = Examples.integer_column / 10
/ : Column | Any -> Column
/ other = run_vectorized_binary_op self '/' (/) other
/ self other = run_vectorized_binary_op self '/' (/) other
## ALIAS AND Columns
@ -380,7 +380,7 @@ type Column
example_and = Examples.bool_column_1 && True
&& : Column | Any -> Column
&& other =
&& self other =
run_vectorized_binary_op self "&&" (&&) other
## ALIAS OR Columns
@ -410,7 +410,7 @@ type Column
example_or = Examples.bool_column_1 || True
|| : Column | Any -> Column
|| other =
|| self other =
run_vectorized_binary_op self "||" (||) other
## ALIAS NOT Columns
@ -424,7 +424,7 @@ type Column
example_not = Examples.bool_column_1.not
not : Column
not = run_vectorized_unary_op self "not" .not
not self = run_vectorized_unary_op self "not" .not
## Returns a column of booleans, with `True` items at the positions where
this column contains a `Nothing`.
@ -436,7 +436,7 @@ type Column
example_is_missing = Examples.decimal_column.is_missing
is_missing : Column
is_missing = run_vectorized_unary_op self "is_missing" (== Nothing)
is_missing self = run_vectorized_unary_op self "is_missing" (== Nothing)
## Returns a column of booleans, with `True` items at the positions where
this column does not contain a `Nothing`.
@ -448,7 +448,7 @@ type Column
example_is_present = Examples.decimal_column.is_present
is_present : Column
is_present = self.is_missing.not
is_present self = self.is_missing.not
## ALIAS Fill Missing
@ -467,7 +467,7 @@ type Column
example_fill_missing = Examples.decimal_column.fill_missing 20.5
fill_missing : Column | Any -> Column
fill_missing default =
fill_missing self default =
storage = self.java_column.getStorage
index = self.java_column.getIndex
name = self.java_column.getName
@ -491,7 +491,7 @@ type Column
example_drop_missing = Examples.decimal_column.drop_missing
drop_missing : Any -> Column
drop_missing =
drop_missing self =
self.where self.is_missing.not
## Checks for each element of the column if it starts with `other`.
@ -517,7 +517,7 @@ type Column
example_starts_with = Examples.text_column_1.starts_with "hell"
starts_with : Column | Text -> Column
starts_with other =
starts_with self other =
run_vectorized_binary_op self "starts_with" (a -> b -> a.starts_with b) other
## Checks for each element of the column if it ends with `other`.
@ -543,7 +543,7 @@ type Column
example_ends_with = Examples.text_column_1.ends_with "hell"
ends_with : Column | Text -> Column
ends_with other =
ends_with self other =
run_vectorized_binary_op self "ends_with" (a -> b -> a.ends_with b) other
## Checks for each element of the column if it contains `other`.
@ -569,7 +569,7 @@ type Column
example_contains = Examples.text_column_1.contains "hell"
contains : Column | Text -> Column
contains other =
contains self other =
run_vectorized_binary_op self "contains" (a -> b -> a.contains b) other
## ALIAS Transform Column
@ -587,7 +587,7 @@ type Column
example_map = Examples.integer_column.map (x -> x * x)
map : (Any -> Any) -> Column
map function =
map self function =
storage = self.java_column.getStorage
index = self.java_column.getIndex
new_st = storage.map Nothing function
@ -617,7 +617,7 @@ type Column
example_zip =
Examples.integer_column.zip Examples.text_column_1 [_, _]
zip : Column -> (Any -> Any -> Any) -> Boolean -> Column
zip that function skip_missing=True =
zip self that function skip_missing=True =
s1 = self.java_column.getStorage
ix = self.java_column.getIndex
s2 = that.java_column.getStorage
@ -639,7 +639,7 @@ type Column
example_rename = Examples.integer_column.rename "My Numbers"
rename : Text -> Column
rename name = Column (self.java_column.rename name)
rename self name = Column (self.java_column.rename name)
## Returns the name of this column.
@ -650,7 +650,7 @@ type Column
example_name = Examples.text_column_2.name
name : Text
name = self.java_column.getName
name self = self.java_column.getName
## Returns the length of this column.
@ -661,7 +661,7 @@ type Column
example_length = Examples.text_column_2.length
length : Integer
length = self.java_column . getSize
length self = self.java_column . getSize
## Returns the number of missing items in this column.
@ -672,7 +672,7 @@ type Column
example_count_missing = Examples.text_column_2.count_missing
count_missing : Integer
count_missing = self.java_column.getStorage.countMissing
count_missing self = self.java_column.getStorage.countMissing
## Returns the number of non-null items in this column.
@ -683,7 +683,7 @@ type Column
example_count = Examples.text_column_2.count
count : Integer
count = self.length - self.count_missing
count self = self.length - self.count_missing
## Returns the index of this column, as a column (indexed by itself).
@ -696,7 +696,7 @@ type Column
example_index = Examples.decimal_column.index
index : Column ! Table.No_Index_Set_Error
index = case self.java_column.getIndex.toColumn of
index self = case self.java_column.getIndex.toColumn of
Nothing -> Error.throw Table.No_Index_Set_Error
i -> Column i
@ -713,7 +713,7 @@ type Column
example_set_index =
Examples.decimal_column.set_index Examples.integer_column
set_index : Column -> Column
set_index index = Column (self.java_column.setIndex index.java_column)
set_index self index = Column (self.java_column.setIndex index.java_column)
## Returns the value contained in this column at the given index.
@ -730,7 +730,7 @@ type Column
example_at = Examples.integer_column.at 0
at : Integer -> (Any | Nothing) ! Index_Out_Of_Bounds_Error
at index =
at self index =
valid_index = (index >= 0) && (index < self.length)
if valid_index.not then Error.throw (Index_Out_Of_Bounds_Error index self.length) else
storage = self.java_column.getStorage
@ -755,7 +755,7 @@ type Column
example_where =
Examples.text_column_1.where (Examples.text_column_1.map .length > 2)
where : Column -> Column
where indexes =
where self indexes =
Column (self.java_column.mask indexes.java_column)
## Returns a vector containing all the elements in this column.
@ -767,7 +767,7 @@ type Column
example_to_vector = Examples.integer_column.to_vector
to_vector : Vector
to_vector = Vector.Vector self.java_column.getStorage.toList
to_vector self = Vector.Vector self.java_column.getStorage.toList
## Returns the underlying storage type of this column.
@ -778,7 +778,7 @@ type Column
example_storage_type = Examples.integer_column.storage_type
storage_type : Storage.Type
storage_type =
storage_type self =
tp = self.java_column.getStorage.getType
if tp == storage_type_string then Storage.Text else
if tp == storage_type_long then Storage.Integer else
@ -797,7 +797,7 @@ type Column
example_to_json = Examples.integer_column.to_json
to_json : Json
to_json =
to_json self =
col = self.java_column
name = col.getName
storage = col.getStorage
@ -837,7 +837,7 @@ type Column
example_join = Examples.integer_column.join Examples.bool_column_1
join : Table.Table | Column -> Text | Nothing -> Boolean -> Text -> Text -> Table
join other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' =
join self other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' =
self.to_table.join other on drop_unmatched left_suffix right_suffix
## Converts this column into a single-column table.
@ -849,7 +849,7 @@ type Column
example_to_table = Examples.integer_column.to_table
to_table : Table.Table
to_table = Table.Table self.java_column.toTable
to_table self = Table.Table self.java_column.toTable
## UNSTABLE
ADVANCED
@ -857,7 +857,7 @@ type Column
Shows a JSON serialization of a truncated version of this column, for the
benefit of visualization in the IDE.
to_default_visualization_data : Text
to_default_visualization_data =
to_default_visualization_data self =
size = ['length', self.length]
name = ['name', self.name]
max_data = 100
@ -875,7 +875,7 @@ type Column
example_sum = Examples.integer_column.sum
sum : Any
sum = self.java_column.aggregate 'sum' (x-> Vector.Vector x . reduce (+)) True
sum self = self.java_column.aggregate 'sum' (x-> Vector.Vector x . reduce (+)) True
## ALIAS Max Columns
@ -888,7 +888,7 @@ type Column
example_max = Examples.integer_column.max
max : Any
max =
max self =
self.java_column.aggregate 'max' (x-> Vector.Vector x . reduce Math.max) True
## ALIAS Min Columns
@ -902,7 +902,7 @@ type Column
example_min = Examples.integer_column.min
min : Any
min =
min self =
self.java_column.aggregate 'min' (x-> Vector.Vector x . reduce Math.min) True
## ALIAS Mean Columns
@ -916,7 +916,7 @@ type Column
example_mean = Examples.integer_column.mean
mean : Any
mean =
mean self =
vec_mean v = if v.length == 0 then Nothing else
(Vector.Vector v).reduce (+) / v.length
self.java_column.aggregate 'mean' vec_mean True
@ -928,7 +928,7 @@ type Column
missing degrees of freedom in the sample. The default value of `1`
computes a sample variance. Setting it to `0` will compute population
variance instead.
variance degrees_of_freedom_correction=1 =
variance self degrees_of_freedom_correction=1 =
mean = self.mean
shifted = self - mean
sq = shifted * shifted
@ -941,14 +941,14 @@ type Column
missing degrees of freedom in the sample. The default value of `1`
computes a sample standard deviation. Setting it to `0` will compute
population standard deviation instead.
standard_deviation degrees_of_freedom_correction=1 =
standard_deviation self degrees_of_freedom_correction=1 =
self.variance degrees_of_freedom_correction . sqrt
## Computes the coefficient of determination of a given prediction column.
Arguments:
- predictions: the column predicting the values of this column.
r_squared predictions =
r_squared self predictions =
prediction_diff = self - predictions
ss_res = prediction_diff*prediction_diff . sum
ss_tot_lin = self - self.mean
@ -996,7 +996,7 @@ type Column
my_comparator a b = a.abs.compare_to b.abs
Examples.decimal_column.sort comparator=my_comparator
sort : Sort_Direction -> Boolean -> (Any -> Any -> Ordering) | Nothing -> Column
sort order=Sort_Direction.Ascending missing_last=True comparator=Nothing =
sort self order=Sort_Direction.Ascending missing_last=True comparator=Nothing =
order_bool = case order of
Sort_Direction.Ascending -> True
Sort_Direction.Descending -> False
@ -1023,7 +1023,7 @@ type Column
example_take_start = Examples.integer_column.take_start 2
take_start : Integer -> Column
take_start count =
take_start self count =
Column (self.java_column.slice 0 count)
## UNSTABLE
@ -1043,7 +1043,7 @@ type Column
example_take_end = Examples.integer_column.take_end 2
take_end : Integer -> Column
take_end count =
take_end self count =
start_point = Math.max (self.length - count) 0
Column (self.java_column.slice start_point count)
@ -1061,7 +1061,7 @@ type Column
example_first = Examples.integer_column.first
first : Any ! Empty_Error
first = self.at 0 . catch Index_Out_Of_Bounds_Error (_ -> Error.throw Empty_Error)
first self = self.at 0 . catch Index_Out_Of_Bounds_Error (_ -> Error.throw Empty_Error)
## UNSTABLE
@ -1077,7 +1077,7 @@ type Column
example_head = Examples.integer_column.head
head : Any ! Empty_Error
head = self.first
head self = self.first
## UNSTABLE
@ -1093,7 +1093,7 @@ type Column
example_last = Examples.integer_column.last
last : Any ! Empty_Error
last = self.at (self.length - 1) . catch Index_Out_Of_Bounds_Error (_ -> Error.throw Empty_Error)
last self = self.at (self.length - 1) . catch Index_Out_Of_Bounds_Error (_ -> Error.throw Empty_Error)
## UNSTABLE
@ -1107,7 +1107,7 @@ type Column
example_reverse = Examples.integer_column.reverse
reverse : Column
reverse =
reverse self =
mask = OrderBuilder.buildReversedMask self.length
Column <| self.java_column.applyMask mask
@ -1123,7 +1123,7 @@ type Column
example_duplicate_count = Examples.integer_column.duplicate_count
duplicate_count : Column
duplicate_count = Column self.java_column.duplicateCount
duplicate_count self = Column self.java_column.duplicateCount
## Wraps a column grouped by its index. Allows performing aggregation operations
on the contained values.
@ -1152,7 +1152,7 @@ type Aggregate_Column
example_reduce =
Examples.aggregate_column.reduce .length . rename "transaction_count"
reduce : (Vector.Vector -> Any) -> Boolean -> Text -> Column
reduce function skip_missing=True name_suffix="_result" =
reduce self function skip_missing=True name_suffix="_result" =
f arr = function (Vector.Vector arr)
r = self.java_column.aggregate Nothing name_suffix f skip_missing
Column r
@ -1171,7 +1171,7 @@ type Aggregate_Column
example_sum = Examples.aggregate_column.sum . rename "id_sum"
sum : Text -> Column
sum name_suffix='_sum' =
sum self name_suffix='_sum' =
r = self.java_column.aggregate 'sum' name_suffix (x-> Vector.Vector x . reduce (+)) True
Column r
@ -1188,7 +1188,7 @@ type Aggregate_Column
example_max = Examples.aggregate_column.max . rename "latest_transaction"
max : Text -> Column
max name_suffix='_max' =
max self name_suffix='_max' =
r = self.java_column.aggregate 'max' name_suffix (x-> Vector.Vector x . reduce Math.max) True
Column r
@ -1205,7 +1205,7 @@ type Aggregate_Column
example_min = Examples.aggregate_column.min . rename "first_transaction"
min : Text -> Column
min name_suffix='_min' =
min self name_suffix='_min' =
r = self.java_column.aggregate 'min' name_suffix (x-> Vector.Vector x . reduce Math.min) True
Column r
@ -1223,7 +1223,7 @@ type Aggregate_Column
example_count = Examples.aggregate_column.count . rename "transaction_count"
count : Text -> Column
count name_suffix='_count' =
count self name_suffix='_count' =
r = self.java_column.aggregate 'count' name_suffix (x-> x.length) True
Column r
@ -1240,7 +1240,7 @@ type Aggregate_Column
example_mean = Examples.aggregate_column.mean
mean : Text -> Column
mean name_suffix='_mean' =
mean self name_suffix='_mean' =
vec_mean v = if v.length == 0 then Nothing else
(Vector.Vector v).reduce (+) / v.length
r = self.java_column.aggregate 'mean' name_suffix vec_mean True
@ -1260,7 +1260,7 @@ type Aggregate_Column
example_values = Examples.aggregate_column.values
values : Text -> Column
values name_suffix='_values' =
values self name_suffix='_values' =
r = self.java_column.aggregate Nothing name_suffix Vector.Vector False
Column r
@ -1277,7 +1277,7 @@ type Aggregate_Column
example_print = Examples.aggregate_column.print
print : Nothing
print = self.values.print
print self = self.values.print
## UNSTABLE
@ -1292,7 +1292,7 @@ type Index_Out_Of_Bounds_Error index length
Pretty-prints the index out of bounds error.
Index_Out_Of_Bounds_Error.to_display_text : Text
Index_Out_Of_Bounds_Error.to_display_text =
Index_Out_Of_Bounds_Error.to_display_text self =
ix_text = self.index.to_text
len_text = self.length.to_text
"The index " + ix_text + " is out of bounds in a column of length " + len_text + "."
@ -1306,7 +1306,7 @@ type Empty_Error
Pretty prints the error.
Empty_Error.to_display_text : Text
Empty_Error.to_display_text = "The column is empty."
Empty_Error.to_display_text self = "The column is empty."
## PRIVATE

View File

@ -68,7 +68,7 @@ type Data_Formatter
If set to `Report_Error`, the operation fails with a dataflow error.
If set to `Ignore`, the operation proceeds without errors or warnings.
parse : Text -> (Auto|Integer|Number|Date|Time|DateTime|Boolean) -> Problem_Behavior -> Any
parse text datatype=Auto on_problems=Problem_Behavior.Report_Warning =
parse self text datatype=Auto on_problems=Problem_Behavior.Report_Warning =
parser = case datatype of
Auto -> self.make_auto_parser
_ -> self.make_datatype_parser datatype
@ -81,7 +81,7 @@ type Data_Formatter
Arguments:
- value: Value to format.
format : Any -> Text
format value =
format self value =
formatter = self.make_auto_formatter
formatter.format value
@ -93,7 +93,7 @@ type Data_Formatter
- allow_leading_zeros: Specifies if values starting with leading zeroes should be treated as numbers.
- allow_exponential_notation: Allow parsing of exponential notation format.
with_number_formatting : Text -> Text -> Boolean -> Boolean -> Data_Formatter
with_number_formatting (decimal_point=self.decimal_point) (thousand_separator=self.thousand_separator) (allow_leading_zeros=self.allow_leading_zeros) (allow_exponential_notation=self.allow_exponential_notation) =
with_number_formatting self (decimal_point=self.decimal_point) (thousand_separator=self.thousand_separator) (allow_leading_zeros=self.allow_leading_zeros) (allow_exponential_notation=self.allow_exponential_notation) =
self.clone decimal_point=decimal_point thousand_separator=thousand_separator allow_leading_zeros=allow_leading_zeros allow_exponential_notation=allow_exponential_notation
## Specify values for Date/Time parsing.
@ -103,7 +103,7 @@ type Data_Formatter
- date_formats: Expected date formats.
- time_formats: Expected time formats.
with_datetime_formats : (Text|[Text]) -> (Text|[Text]) -> (Text|[Text]) -> Data_Formatter
with_datetime_formats datetime_formats=self.datetime_formats date_formats=self.date_formats time_formats=self.time_formats =
with_datetime_formats self datetime_formats=self.datetime_formats date_formats=self.date_formats time_formats=self.time_formats =
datetime_vector = if datetime_formats.is_a Text then [datetime_formats] else datetime_formats
date_vector = if date_formats.is_a Text then [date_formats] else date_formats
time_vector = if time_formats.is_a Text then [time_formats] else time_formats
@ -115,7 +115,7 @@ type Data_Formatter
- true_values: Values representing True.
- false_values: Values representing False.
with_boolean_values : (Text|[Text]) -> (Text|[Text]) -> Data_Formatter
with_boolean_values true_values false_values =
with_boolean_values self true_values false_values =
true_vector = if true_values.is_a Text then [true_values] else true_values
false_vector = if false_values.is_a Text then [false_values] else false_values
self.clone true_values=true_vector false_values=false_vector
@ -125,52 +125,52 @@ type Data_Formatter
Arguments:
- locale: The locale to use when parsing dates and times.
with_locale : Locale -> Delimited
with_locale datetime_locale = self.clone datetime_locale=datetime_locale
with_locale self datetime_locale = self.clone datetime_locale=datetime_locale
## PRIVATE
Clone the instance with some properties overridden.
clone : Boolean->Boolean->Text->Text->Boolean->[Text]->[Text]->[Text]->Locale->[Text]->[Text]->Data_Formatter
clone (trim_values=self.trim_values) (allow_leading_zeros=self.allow_leading_zeros) (decimal_point=self.decimal_point) (thousand_separator=self.thousand_separator) (allow_exponential_notation=self.allow_exponential_notation) (datetime_formats=self.datetime_formats) (date_formats=self.date_formats) (time_formats=self.time_formats) (datetime_locale=self.datetime_locale) (true_values=self.true_values) (false_values=self.false_values) =
clone self (trim_values=self.trim_values) (allow_leading_zeros=self.allow_leading_zeros) (decimal_point=self.decimal_point) (thousand_separator=self.thousand_separator) (allow_exponential_notation=self.allow_exponential_notation) (datetime_formats=self.datetime_formats) (date_formats=self.date_formats) (time_formats=self.time_formats) (datetime_locale=self.datetime_locale) (true_values=self.true_values) (false_values=self.false_values) =
Data_Formatter trim_values=trim_values allow_leading_zeros=allow_leading_zeros decimal_point=decimal_point thousand_separator=thousand_separator allow_exponential_notation=allow_exponential_notation datetime_formats=datetime_formats date_formats=date_formats time_formats=time_formats datetime_locale=datetime_locale true_values=true_values false_values=false_values
## PRIVATE
get_thousand_separator =
get_thousand_separator self =
if self.thousand_separator.is_empty then Nothing else self.thousand_separator
## PRIVATE
wrap_base_parser base_parser =
wrap_base_parser self base_parser =
if self.trim_values.not then base_parser else
WhitespaceStrippingParser.new base_parser
## PRIVATE
make_integer_parser = self.wrap_base_parser <|
make_integer_parser self = self.wrap_base_parser <|
IntegerParser.new self.get_thousand_separator self.allow_leading_zeros
## PRIVATE
make_decimal_parser = self.wrap_base_parser <|
make_decimal_parser self = self.wrap_base_parser <|
DecimalParser.new self.decimal_point self.get_thousand_separator self.allow_leading_zeros self.allow_exponential_notation
## PRIVATE
make_boolean_parser = self.wrap_base_parser <|
make_boolean_parser self = self.wrap_base_parser <|
BooleanParser.new self.true_values.to_array self.false_values.to_array
## PRIVATE
make_date_parser = self.wrap_base_parser <|
make_date_parser self = self.wrap_base_parser <|
DateParser.new self.date_formats.to_array self.datetime_locale.java_locale
## PRIVATE
make_datetime_parser = self.wrap_base_parser <|
make_datetime_parser self = self.wrap_base_parser <|
DateTimeParser.new self.datetime_formats.to_array self.datetime_locale.java_locale
## PRIVATE
make_time_parser = self.wrap_base_parser <|
make_time_parser self = self.wrap_base_parser <|
TimeParser.new self.time_formats.to_array self.datetime_locale.java_locale
## PRIVATE
make_identity_parser = self.wrap_base_parser IdentityParser.new
make_identity_parser self = self.wrap_base_parser IdentityParser.new
## PRIVATE
make_datatype_parser datatype = case datatype of
make_datatype_parser self datatype = case datatype of
Integer -> self.make_integer_parser
Decimal -> self.make_decimal_parser
Boolean -> self.make_boolean_parser
@ -181,59 +181,59 @@ type Data_Formatter
Error.throw (Illegal_Argument_Error "Unsupported datatype: "+datatype.to_text)
## PRIVATE
get_specific_type_parsers =
get_specific_type_parsers self =
[self.make_integer_parser, self.make_decimal_parser, self.make_datetime_parser, self.make_date_parser, self.make_time_parser, self.make_boolean_parser]
## PRIVATE
make_auto_parser =
make_auto_parser self =
fallback_parser = self.make_identity_parser
TypeInferringParser.new self.get_specific_type_parsers.to_array fallback_parser
## PRIVATE
make_integer_formatter =
make_integer_formatter self =
IntegerFormatter.new self.get_thousand_separator
## PRIVATE
make_decimal_formatter =
make_decimal_formatter self =
DecimalFormatter.new self.get_thousand_separator self.decimal_point
## PRIVATE
make_date_formatter =
make_date_formatter self =
if self.date_formats.is_empty then Error.throw (Illegal_Argument_Error "Formatting dates requires at least one entry in the `date_formats` parameter") else
DateFormatter.new self.date_formats.first self.datetime_locale.java_locale
## PRIVATE
make_time_formatter =
make_time_formatter self =
if self.time_formats.is_empty then Error.throw (Illegal_Argument_Error "Formatting times requires at least one entry in the `time_formats` parameter") else
TimeFormatter.new self.time_formats.first self.datetime_locale.java_locale
## PRIVATE
make_datetime_formatter =
make_datetime_formatter self =
if self.datetime_formats.is_empty then Error.throw (Illegal_Argument_Error "Formatting date-times requires at least one entry in the `datetime_formats` parameter") else
DateTimeFormatter.new self.datetime_formats.first self.datetime_locale.java_locale
## PRIVATE
make_boolean_formatter =
make_boolean_formatter self =
if self.true_values.is_empty then Error.throw (Illegal_Argument_Error "Formatting booleans requires at least one entry in the `true_values` parameter") else
if self.false_values.is_empty then Error.throw (Illegal_Argument_Error "Formatting booleans requires at least one entry in the `false_values` parameter") else
BooleanFormatter.new self.true_values.first self.false_values.first
## PRIVATE
make_text_formatter =
make_text_formatter self =
TextFormatter.new
## PRIVATE
get_specific_type_formatters =
get_specific_type_formatters self =
[self.make_integer_formatter, self.make_decimal_formatter, self.make_boolean_formatter, self.make_datetime_formatter, self.make_date_formatter, self.make_time_formatter, self.make_text_formatter]
## PRIVATE
make_auto_formatter =
make_auto_formatter self =
# TODO The panic rethrow+recover is a workaround for the vector error propagation bug.
formatters = Panic.recover Illegal_Argument_Error (self.get_specific_type_formatters.map Panic.rethrow)
AnyObjectFormatter.new formatters.to_array
## PRIVATE
make_formatter_for_column_type (column_type : Storage) = case column_type of
make_formatter_for_column_type self (column_type : Storage) = case column_type of
Storage.Text -> self.make_text_formatter
Storage.Integer -> self.make_integer_formatter
Storage.Decimal -> self.make_decimal_formatter

View File

@ -155,7 +155,7 @@ type Table
example_display = Examples.inventory_table.display
display : Integer -> Boolean -> Text
display show_rows=10 format_terminal=False =
display self show_rows=10 format_terminal=False =
cols = Vector.Vector self.java_table.getColumns
index = self.java_table.getIndex
col_names = [index.getName] + cols.map .getName
@ -183,7 +183,7 @@ type Table
import Standard.Examples
example_print = Examples.inventory_table.print
print show_rows=10 =
print self show_rows=10 =
IO.println (self.display show_rows format_terminal=True)
IO.println ''
@ -196,7 +196,7 @@ type Table
example_to_json = Examples.inventory_table.to_json
to_json : Json
to_json =
to_json self =
index_prep = case self.index.catch No_Index_Set_Error (_->Nothing) of
Nothing -> []
index -> [index]
@ -214,7 +214,7 @@ type Table
Returns a JSON object containing useful metadata and previews of column
values.
to_default_visualization_data : Text
to_default_visualization_data =
to_default_visualization_data self =
max_size = 10
row_count = ['number_of_rows', self.row_count]
cols = self.columns.map c->
@ -229,7 +229,7 @@ type Table
Guides the visualization system to display the most suitable graphical
representation for this table.
default_visualization : Visualization.Id.Id
default_visualization =
default_visualization self =
cols = self.columns.map .name . map name-> name.to_case Case.Lower
if cols.contains "latitude" && cols.contains "longitude" then Visualization.Id.geo_map else
if cols.contains "x" && cols.contains "y" then Visualization.Id.scatter_plot else
@ -247,7 +247,7 @@ type Table
example_at = Examples.inventory_table.at "item_name"
at : Text -> Column ! No_Such_Column_Error
at name = case self.java_table.getColumnOrIndexByName name of
at self name = case self.java_table.getColumnOrIndexByName name of
Nothing -> Error.throw (No_Such_Column_Error name)
c -> Column.Column c
@ -298,7 +298,7 @@ type Table
table.select_columns (By_Column [column1, column2])
select_columns : Column_Selector -> Boolean -> Problem_Behavior -> Table
select_columns (columns = By_Index [0]) (reorder = False) (on_problems = Report_Warning) =
select_columns self (columns = By_Index [0]) (reorder = False) (on_problems = Report_Warning) =
new_columns = Table_Helpers.select_columns internal_columns=self.columns selector=columns reorder=reorder on_problems=on_problems
new new_columns
@ -347,7 +347,7 @@ type Table
table.remove_columns (By_Column [column1, column2])
remove_columns : Column_Selector -> Problem_Behavior -> Table
remove_columns (columns = By_Index [0]) (on_problems = Report_Warning) =
remove_columns self (columns = By_Index [0]) (on_problems = Report_Warning) =
new_columns = Table_Helpers.remove_columns internal_columns=self.columns selector=columns on_problems=on_problems
new new_columns
@ -401,7 +401,7 @@ type Table
table.reorder_columns (By_Column [column1, column2])
reorder_columns : Column_Selector -> Position.Position -> Problem_Behavior -> Table
reorder_columns (columns = By_Index [0]) (position = Position.Before_Other_Columns) (on_problems = Report_Warning) =
reorder_columns self (columns = By_Index [0]) (position = Position.Before_Other_Columns) (on_problems = Report_Warning) =
new_columns = Table_Helpers.reorder_columns internal_columns=self.columns selector=columns position=position on_problems=on_problems
new new_columns
@ -429,7 +429,7 @@ type Table
table.reorder_columns Sort_Direction.Descending
sort_columns : Sort_Direction -> Text_Ordering -> Table
sort_columns direction=Sort_Direction.Ascending text_ordering=Text_Ordering =
sort_columns self direction=Sort_Direction.Ascending text_ordering=Text_Ordering =
new_columns = Table_Helpers.sort_columns internal_columns=self.columns direction text_ordering
new new_columns
@ -461,7 +461,7 @@ type Table
table.rename_columns (Column_Name_Mapping.By_Position ["FirstColumn"])
rename_columns : Column_Name_Mapping -> Problem_Behavior -> Table
rename_columns (column_map=(Column_Name_Mapping.By_Position ["Column"])) (on_problems=Report_Warning) =
rename_columns self (column_map=(Column_Name_Mapping.By_Position ["Column"])) (on_problems=Report_Warning) =
new_names = Table_Helpers.rename_columns internal_columns=self.columns mapping=column_map on_problems=on_problems
if new_names.is_error then new_names else
new_columns = self.columns.map_with_index i->c->(c.rename (new_names.at i))
@ -485,7 +485,7 @@ type Table
table.use_first_row_as_names
use_first_row_as_names : Problem_Behavior -> Table
use_first_row_as_names (on_problems=Report_Warning) =
use_first_row_as_names self (on_problems=Report_Warning) =
mapper = col->
val = col.at 0
case val of
@ -521,7 +521,7 @@ type Table
table.aggregate [Group_By "Key", Count Nothing]
aggregate : [Aggregate_Column] -> Problem_Behavior -> Table
aggregate columns (on_problems=Report_Warning) =
aggregate self columns (on_problems=Report_Warning) =
validated = Aggregate_Column_Helper.prepare_aggregate_columns columns self
on_problems.attach_problems_before validated.problems <|
@ -607,7 +607,7 @@ type Table
table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "total_stock", Sort_Column.Name "sold_stock" Sort_Direction.Descending])
order_by : Sort_Column_Selector -> Text_Ordering -> Problem_Behavior -> Table
order_by (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering on_problems=Report_Warning =
order_by self (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering on_problems=Report_Warning =
problem_builder = Problem_Builder.new
columns_for_ordering = Table_Helpers.prepare_order_by self.columns columns problem_builder
problem_builder.attach_problems_before on_problems <|
@ -628,7 +628,7 @@ type Table
a leading 0). However, settings in the `Data_Formatter` can
control this.
parse_values : Data_Formatter -> (Nothing | [Column_Type_Selection]) -> Problem_Behavior -> Table
parse_values value_formatter=Data_Formatter column_types=Nothing on_problems=Report_Warning =
parse_values self value_formatter=Data_Formatter column_types=Nothing on_problems=Report_Warning =
columns = self.columns
problem_builder = Vector.new_builder
@ -708,7 +708,7 @@ type Table
mask = (table.at "sold_stock" > (table.at "total_stock" / 2))
table.where mask
where : Column -> Table
where indexes =
where self indexes =
Table (self.java_table.mask indexes.java_column)
## ALIAS Add Column
@ -733,7 +733,7 @@ type Table
double_inventory = table.at "total_stock" * 2
table.set "total_stock" double_inventory
set : Text -> Column.Column | Vector.Vector -> Table
set name column = case column of
set self name column = case column of
Vector.Vector _ ->
self.set name (Column.from_vector name column)
Column.Column _ ->
@ -748,7 +748,7 @@ type Table
example_columns = Examples.inventory_table.columns
columns : Vector
columns = Vector.Vector self.java_table.getColumns . map Column.Column
columns self = Vector.Vector self.java_table.getColumns . map Column.Column
## Sets the index of this table, using the column with the provided name.
@ -763,7 +763,7 @@ type Table
example_set_index = Examples.inventory_table.set_index "item_name"
set_index : Text | Column -> Table
set_index index = case index of
set_index self index = case index of
Text -> Table (self.java_table.indexFromColumn index)
Column.Column c -> Table (self.java_table.indexFromColumn c)
@ -779,7 +779,7 @@ type Table
example_index = Examples.inventory_table.index
index : Column.Column ! No_Index_Set_Error
index = case self.java_table.getIndex.toColumn of
index self = case self.java_table.getIndex.toColumn of
Nothing -> Error.throw No_Index_Set_Error
i -> Column.Column i
@ -813,7 +813,7 @@ type Table
example_join =
Examples.inventory_table.join Examples.popularity_table
join : Table | Column.Column -> Text | Nothing -> Boolean -> Text -> Text -> Table
join other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' =
join self other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' =
case other of
Column.Column _ -> self.join other.to_table on drop_unmatched left_suffix right_suffix
Table t ->
@ -832,7 +832,7 @@ type Table
example_drop_missing_rows =
Examples.inventory_table.drop_missing_rows
drop_missing_rows : Table
drop_missing_rows =
drop_missing_rows self =
cols = self.columns
case cols.not_empty of
True ->
@ -853,7 +853,7 @@ type Table
example_drop_missing_cols =
Examples.inventory_table.drop_missing_columns
drop_missing_columns : Table
drop_missing_columns =
drop_missing_columns self =
non_missing = self.columns . filter (col -> col.count_missing == 0)
index = self.java_table.getIndex
Table (Java_Table.new (non_missing.map .java_column . to_array) index)
@ -867,7 +867,7 @@ type Table
example_row_count = Examples.inventory_table.row_count
row_count : Integer
row_count = self.java_table.rowCount
row_count self = self.java_table.rowCount
## Returns the number of rows in this table.
@ -878,7 +878,7 @@ type Table
example_length = Examples.inventory_table.length
length : Integer
length = self.row_count
length self = self.row_count
## Returns a Table describing this table's contents.
@ -892,7 +892,7 @@ type Table
example_info = Examples.inventory_table.info
info : Table
info =
info self =
cols = self.columns
new [["Column", cols.map .name], ["Items Count", cols.map .count], ["Storage Type", cols.map .storage_type]] . set_index "Column"
@ -914,7 +914,7 @@ type Table
example_concat =
Examples.inventory_table.concat Examples.popularity_table
concat : Table -> Table
concat other = Table (Java_Table.concat [self.java_table, other.java_table].to_array)
concat self other = Table (Java_Table.concat [self.java_table, other.java_table].to_array)
## ALIAS First N Rows
UNSTABLE
@ -934,7 +934,7 @@ type Table
example_take_start = Examples.inventory_table.take_start 4
take_start : Integer -> Table
take_start count = Table (self.java_table.slice 0 count)
take_start self count = Table (self.java_table.slice 0 count)
## ALIAS Last N Rows
UNSTABLE
@ -954,7 +954,7 @@ type Table
example_take_end = Examples.inventory_table.take_end 4
take_end : Integer -> Table
take_end count =
take_end self count =
start_point = Math.max (self.row_count - count) 0
Table (self.java_table.slice start_point count)
@ -973,7 +973,7 @@ type Table
example_first = Examples.inventory_table.first
first : Table ! Empty_Error
first =
first self =
table = self.take_start 1
if table.row_count != 1 then Error.throw Empty_Error else table
@ -991,7 +991,7 @@ type Table
example_head = Examples.inventory_table.head
head : Table ! Empty_Error
head = self.first
head self = self.first
## ALIAS Last Row
UNSTABLE
@ -1008,7 +1008,7 @@ type Table
example_last = Examples.inventory_table.last
last : Table ! Empty_Error
last =
last self =
table = self.take_end 1
if table.row_count != 1 then Error.throw Empty_Error else table
@ -1024,7 +1024,7 @@ type Table
example_reverse = Examples.inventory_table.reverse
reverse : Table
reverse =
reverse self =
mask = OrderBuilder.buildReversedMask self.row_count
Table <| self.java_table.applyMask mask
@ -1046,7 +1046,7 @@ type Table
example_to_json = Examples.inventory_table.write_json (enso_project.data / 'example.json')
write_json : File.File -> Nothing
write_json file = self.to_json.to_text.write file
write_json self file = self.to_json.to_text.write file
## This function writes a table from memory into a file.
@ -1110,12 +1110,12 @@ type Table
example_to_xlsx = Examples.inventory_table.write (enso_project.data / "example_xlsx_output.xlsx") File_Format.Excel
write : File|Text -> File_Format -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing ! Column_Mismatch | Illegal_Argument_Error | File_Not_Found | IO_Error
write path format=File_Format.Auto on_existing_file=Existing_File_Behavior.Backup match_columns=Match_Columns.By_Name on_problems=Report_Warning =
write self path format=File_Format.Auto on_existing_file=Existing_File_Behavior.Backup match_columns=Match_Columns.By_Name on_problems=Report_Warning =
format.write_table (File.new path) self on_existing_file match_columns on_problems
## Creates a text representation of the table using the CSV format.
to_csv : Text
to_csv = Text.from self (File_Format.Delimited delimiter=",")
to_csv self = Text.from self (File_Format.Delimited delimiter=",")
## UNSTABLE
@ -1130,7 +1130,7 @@ type No_Such_Column_Error column_name
Create a human-readable version of the no such column error.
No_Such_Column_Error.to_display_text : Text
No_Such_Column_Error.to_display_text =
No_Such_Column_Error.to_display_text self =
"The column " + self.column_name + " does not exist."
## UNSTABLE
@ -1142,7 +1142,7 @@ type No_Index_Set_Error
Create a human-readable version of the no such column error.
No_Index_Set_Error.to_display_text : Text
No_Index_Set_Error.to_display_text = "The table does not have an index set."
No_Index_Set_Error.to_display_text self = "The table does not have an index set."
## UNSTABLE
@ -1153,7 +1153,7 @@ type Empty_Error
Pretty prints the error.
Empty_Error.to_display_text : Text
Empty_Error.to_display_text = "The table is empty."
Empty_Error.to_display_text self = "The table is empty."
## PRIVATE
from_columns cols = Table (Java_Table.new cols.to_array)

View File

@ -8,7 +8,7 @@ polyglot java import org.enso.table.error.ColumnNameMismatchException
type Missing_Input_Columns (criteria : [Text])
Missing_Input_Columns.to_display_text : Text
Missing_Input_Columns.to_display_text =
Missing_Input_Columns.to_display_text self =
"The criteria "+self.criteria.to_text+" did not match any columns."
## One or more column indexes were invalid on the input table.
@ -16,7 +16,7 @@ Missing_Input_Columns.to_display_text =
type Column_Indexes_Out_Of_Range (indexes : [Integer])
Column_Indexes_Out_Of_Range.to_display_text : Text
Column_Indexes_Out_Of_Range.to_display_text = case self.indexes.length == 1 of
Column_Indexes_Out_Of_Range.to_display_text self = case self.indexes.length == 1 of
True -> "The index " + (self.indexes.at 0).to_text + " is out of range."
False -> "The indexes "+self.indexes.short_display_text+" are out of range."
@ -25,14 +25,14 @@ Column_Indexes_Out_Of_Range.to_display_text = case self.indexes.length == 1 of
type Too_Many_Column_Names_Provided (column_names : [Text])
Too_Many_Column_Names_Provided.to_display_text : Text
Too_Many_Column_Names_Provided.to_display_text =
Too_Many_Column_Names_Provided.to_display_text self =
"Too many column names provided. " + (self.column_names.at 0).to_text + " unused."
## One or more column names were invalid during a rename operation.
type Invalid_Output_Column_Names (column_names : [Text])
Invalid_Output_Column_Names.to_display_text : Text
Invalid_Output_Column_Names.to_display_text = case self.column_names.length == 1 of
Invalid_Output_Column_Names.to_display_text self = case self.column_names.length == 1 of
True -> "The name " + (self.column_names.at 0).to_text + " is invalid."
False -> "The names "+self.column_names.short_display_text+" are invalid."
@ -40,7 +40,7 @@ Invalid_Output_Column_Names.to_display_text = case self.column_names.length == 1
type Duplicate_Output_Column_Names (column_names : [Text])
Duplicate_Output_Column_Names.to_display_text : Text
Duplicate_Output_Column_Names.to_display_text = case self.column_names.length == 1 of
Duplicate_Output_Column_Names.to_display_text self = case self.column_names.length == 1 of
True -> "The name " + (self.column_names.at 0).to_text + " was repeated in the output, so was renamed."
False -> "The names "+self.column_names.short_display_text+" were repeated in the output, and were renamed."
@ -48,14 +48,14 @@ Duplicate_Output_Column_Names.to_display_text = case self.column_names.length ==
type No_Output_Columns
No_Output_Columns.to_display_text : Text
No_Output_Columns.to_display_text =
No_Output_Columns.to_display_text self =
"The result contains no columns."
## Indicates that the provided Column_Selector has duplicate entries.
type Duplicate_Column_Selectors (duplicate_selectors : [(Text | Integer)])
Duplicate_Column_Selectors.to_display_text : Text
Duplicate_Column_Selectors.to_display_text =
Duplicate_Column_Selectors.to_display_text self =
"The provided Column_Selector has duplicate entries: "+self.duplicate_selectors.short_display_text+"."
## Indicates that one column has been matched by multiple selectors.
@ -65,7 +65,7 @@ Duplicate_Column_Selectors.to_display_text =
type Column_Matched_By_Multiple_Selectors (column_name : Text) (selectors : [Any])
Column_Matched_By_Multiple_Selectors.to_display_text : Text
Column_Matched_By_Multiple_Selectors.to_display_text =
Column_Matched_By_Multiple_Selectors.to_display_text self =
'The column "' + self.column_name + '" is matched by multiple selectors: ' + self.selectors.short_display_text + "."
## Indicates that the provided indices matched columns already matched by
@ -77,7 +77,7 @@ Column_Matched_By_Multiple_Selectors.to_display_text =
type Input_Indices_Already_Matched (indices : [Integer])
Input_Indices_Already_Matched.to_display_text : Text
Input_Indices_Already_Matched.to_display_text =
Input_Indices_Already_Matched.to_display_text self =
"The indices "+self.indices.short_display_text+" matched columns which have been matched earlier by other indices, so they did not introduce any new columns into the result."
## Indicates that no input columns were selected for the operation, so the
@ -85,7 +85,7 @@ Input_Indices_Already_Matched.to_display_text =
type No_Input_Columns_Selected
No_Input_Columns_Selected.to_display_text : Text
No_Input_Columns_Selected.to_display_text =
No_Input_Columns_Selected.to_display_text self =
"No input columns have been selected for the operation."
@ -93,28 +93,28 @@ No_Input_Columns_Selected.to_display_text =
type Invalid_Aggregation (column:Text) (rows:[Integer]) (message:Text)
Invalid_Aggregation.to_display_text : Text
Invalid_Aggregation.to_display_text =
Invalid_Aggregation.to_display_text self =
"The "+self.column+" could not be calculated at "+self.row.to_text+" : "+self.message
## Indicates that a floating point number was used in a grouping.
type Floating_Point_Grouping (column:Text) (rows:[Integer])
Floating_Point_Grouping.to_display_text : Text
Floating_Point_Grouping.to_display_text =
Floating_Point_Grouping.to_display_text self =
"Grouping on floating points is not recommended within "+self.column+" at row "+self.row.to_text+"."
## Indicates that a text value with a delimiter was included in a concatenation without any quote character
type Unquoted_Delimiter (column:Text) (rows:[Integer])
Unquoted_Delimiter.to_display_text : Text
Unquoted_Delimiter.to_display_text =
Unquoted_Delimiter.to_display_text self =
"The "+self.column+" at row "+self.row.to_text+" contains the delimiter and there is no specified quote character."
## Warning when additional warnings occurred.
type Additional_Warnings (count:Integer)
Additional_Warnings.to_display_text : Text
Additional_Warnings.to_display_text =
Additional_Warnings.to_display_text self =
"There were "+self.count.to_text+" additional issues."
## Indicates that when loading a delimited file, a row was encountered which had
@ -138,7 +138,7 @@ type Parser_Error cause
type Invalid_Location (location:Text)
Invalid_Location.to_display_text : Text
Invalid_Location.to_display_text =
Invalid_Location.to_display_text self =
"The location '"+self.location+"' is not valid."
## Indicates that some values did not match the expected datatype format.
@ -152,7 +152,7 @@ Invalid_Location.to_display_text =
type Invalid_Format column:(Text|Nothing) (datatype:(Integer|Number|Date|Time|Time_Of_Day|Boolean)) (cells:[Text])
Invalid_Format.to_display_text : Text
Invalid_Format.to_display_text =
Invalid_Format.to_display_text self =
self.cells.length+" cells in column "+self.column+" had invalid format for datatype "+self.datatype.to_text+"."
## Indicates that some values contained leading zeros even though these were not allowed.
@ -175,7 +175,7 @@ type Duplicate_Type_Selector column:Text ambiguous:Boolean
type Unsupported_File_Type filename
Unsupported_File_Type.to_display_text : Text
Unsupported_File_Type.to_display_text =
Unsupported_File_Type.to_display_text self =
"The "+self.filename+" has a type that is not supported by the Auto format."
## Indicates that the target range contains existing data and the user did not
@ -183,24 +183,24 @@ Unsupported_File_Type.to_display_text =
type Existing_Data message
Existing_Data.to_display_text : Text
Existing_Data.to_display_text = self.message
Existing_Data.to_display_text self = self.message
## Indicates that the specified range is not large enough to fit the data.
type Range_Exceeded message
Range_Exceeded.to_display_text : Text
Range_Exceeded.to_display_text = self.message
Range_Exceeded.to_display_text self = self.message
## Indicates that the existing table has a different number of columns to the
new table.
type Column_Count_Mismatch expected actual
Column_Count_Mismatch.to_display_text : Text
Column_Count_Mismatch.to_display_text =
Column_Count_Mismatch.to_display_text self =
"Expected " + self.expected.to_text + " columns, got " + self.actual.to_text + "."
## PRIVATE
Column_Count_Mismatch.handle_java_exception =
Column_Count_Mismatch.handle_java_exception self =
throw_column_count_mismatch caught_panic =
cause = caught_panic.payload.cause
Error.throw (Column_Count_Mismatch cause.getExpected cause.getActual)
@ -211,7 +211,7 @@ Column_Count_Mismatch.handle_java_exception =
type Column_Name_Mismatch missing extras message
Column_Name_Mismatch.to_display_text : Text
Column_Name_Mismatch.to_display_text = self.message
Column_Name_Mismatch.to_display_text self = self.message
## PRIVATE
Column_Name_Mismatch.handle_java_exception =

View File

@ -47,43 +47,43 @@ type Excel_Range
## Gets the name of the sheet.
sheet_name : Text
sheet_name = self.java_range.getSheetName
sheet_name self = self.java_range.getSheetName
## Gets the index (1-based) of the top row of the range.
Returns `Nothing` if referring to a complete column.
top_row : Integer | Nothing
top_row = if self.java_range.isWholeColumn then Nothing else
top_row self = if self.java_range.isWholeColumn then Nothing else
self.java_range.getTopRow
## Gets the index (1-based) of the bottom row of the range.
Returns `Nothing` if referring to a complete column.
bottom_row : Integer | Nothing
bottom_row = if self.java_range.isWholeColumn then Nothing else
bottom_row self = if self.java_range.isWholeColumn then Nothing else
self.java_range.getBottomRow
## Gets the index (1-based) of the left column of the range.
Returns `Nothing` if referring to a complete row.
left_column : Integer | Nothing
left_column = if self.java_range.isWholeRow then Nothing else
left_column self = if self.java_range.isWholeRow then Nothing else
self.java_range.getLeftColumn
## Gets the index (1-based) of the right column of the range.
Returns `Nothing` if referring to a complete row.
right_column : Integer | Nothing
right_column = if self.java_range.isWholeRow then Nothing else
right_column self = if self.java_range.isWholeRow then Nothing else
self.java_range.getRightColumn
## Is the Excel_Range referring to a single cell
is_single_cell : Boolean
is_single_cell = self.java_range.isSingleCell
is_single_cell self = self.java_range.isSingleCell
## Gets the address to this in A1 format.
address : Text
address = self.java_range.getAddress
address self = self.java_range.getAddress
## Displays the Excel_Range.
to_text : Text
to_text = "Excel_Range " + self.address
to_text self = "Excel_Range " + self.address
## Validates if a column index (1-based) is within the valid range for
Excel.
@ -91,7 +91,7 @@ type Excel_Range
Arguments:
- column: 1-based index to check.
is_valid_column : Integer -> Boolean
is_valid_column column =
is_valid_column self column =
excel_2007_column_limit = 16384
(column > 0) && (column <= excel_2007_column_limit)
@ -100,14 +100,14 @@ type Excel_Range
Arguments:
- row: 1-based index to check.
is_valid_row : Integer -> Boolean
is_valid_row row =
is_valid_row self row =
excel_2007_row_limit = 1048576
(row > 0) && (row <= excel_2007_row_limit)
## Given a column name, parses to the index (1-based) or return index
unchanged.
column_index : (Text|Integer) -> Integer
column_index column =
column_index self column =
if column.is_an Integer then column else Java_Range.parseA1Column column
## Creates a Range from an address.
@ -118,7 +118,7 @@ type Excel_Range
## Create a Range for a single cell.
for_cell : Text -> (Text|Integer) -> Integer -> Excel_Range
for_cell sheet column row =
for_cell self sheet column row =
col_index = Excel_Range.column_index column
col_valid = validate (Excel_Range.is_valid_column col_index) ("Invalid column for Excel: " + column.to_text + ".")
@ -129,7 +129,7 @@ type Excel_Range
## Create an Excel_Range for a range of cells.
for_range : Text -> (Text|Integer) -> Integer -> (Text|Integer) -> Integer -> Excel_Range
for_range sheet left top right bottom =
for_range self sheet left top right bottom =
left_index = Excel_Range.column_index left
right_index = Excel_Range.column_index right
@ -143,7 +143,7 @@ type Excel_Range
## Create an Excel_Range for a set of columns.
for_columns : Text -> (Text|Integer) -> (Text|Integer) -> Excel_Range
for_columns sheet left (right=left) =
for_columns self sheet left (right=left) =
left_index = Excel_Range.column_index left
right_index = Excel_Range.column_index right
@ -155,7 +155,7 @@ type Excel_Range
## Create an Excel_Range for a set of rows.
for_rows : Text -> Integer -> Integer -> Excel_Range
for_rows sheet top (bottom=top) =
for_rows self sheet top (bottom=top) =
top_valid = validate (Excel_Range.is_valid_row top) ("Invalid top row for Excel: " + top.to_text + ".")
bottom_valid = validate (Excel_Range.is_valid_row bottom) ("Invalid bottom row for Excel: " + bottom.to_text + ".")

View File

@ -26,7 +26,7 @@ type Auto
## ADVANCED
Gets the underlying File_Format for the specified file
materialise : File->File_Format
materialise file =
materialise self file =
extension = file.extension
output = Ref.new Nothing
@ -44,13 +44,13 @@ type Auto
## Implements the `File.read` for this `File_Format`
read : File -> Problem_Behavior -> Any
read file on_problems =
read self file on_problems =
materialised = self.materialise file
materialised.read file on_problems
## Implements the `Table.write` for this `File_Format`.
write_table : File -> Table -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing
write_table file table on_existing_file match_columns on_problems =
write_table self file table on_existing_file match_columns on_problems =
materialised = self.materialise file
materialised.write_table file table on_existing_file match_columns on_problems
@ -60,12 +60,12 @@ type Bytes
## Implements the `File.read` for this `File_Format`
read : File -> Problem_Behavior -> Any
read file _ =
read self file _ =
file.read_bytes
## Implements the `Table.write` for this `File_Format`.
write_table : File -> Table -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing
write_table _ _ _ _ _ =
write_table self _ _ _ _ _ =
Error.throw (Illegal_Argument_Error "Saving a Table as Bytes is not supported.")
## Reads the file to a `Text` with specified encoding.
@ -74,12 +74,12 @@ type Plain_Text
## Implements the `File.read` for this `File_Format`
read : File -> Problem_Behavior -> Any
read file on_problems =
read self file on_problems =
file.read_text self.encoding on_problems
## Implements the `Table.write` for this `File_Format`.
write_table : File -> Table -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing
write_table _ _ _ _ _ =
write_table self _ _ _ _ _ =
Error.throw (Illegal_Argument_Error "Saving a Table as Plain_Text is not directly supported. You may convert the Table to a Text using `Text.from` and then use `Text.write` to write it.")
## Read delimited files such as CSVs into a Table.
@ -124,65 +124,65 @@ type Delimited
## Implements the `File.read` for this `File_Format`
read : File -> Problem_Behavior -> Any
read file on_problems =
read self file on_problems =
Delimited_Reader.read_file self file on_problems
## Implements the `Table.write` for this `File_Format`.
write_table : File -> Table -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing
write_table file table on_existing_file match_columns on_problems =
write_table self file table on_existing_file match_columns on_problems =
Delimited_Writer.write_file table self file on_existing_file match_columns on_problems
## PRIVATE
Clone the instance with some properties overridden.
Note: This function is internal until such time as Atom cloning with modification is built into Enso.
clone : Text->Text->(Boolean|Infer)->Data_Formatter->Boolean->(Text|Nothing)->(Text|Nothing)->Delimited
clone (quote_style=self.quote_style) (headers=self.headers) (value_formatter=self.value_formatter) (keep_invalid_rows=self.keep_invalid_rows) (line_endings=self.line_endings) (comment_character=self.comment_character) =
clone self (quote_style=self.quote_style) (headers=self.headers) (value_formatter=self.value_formatter) (keep_invalid_rows=self.keep_invalid_rows) (line_endings=self.line_endings) (comment_character=self.comment_character) =
Delimited self.delimiter self.encoding self.skip_rows self.row_limit quote_style headers value_formatter keep_invalid_rows line_endings comment_character
## Create a clone of this with specified quoting settings.
with_quotes : Text->Text->Boolean->Delimited
with_quotes quote='"' quote_escape=quote always_quote=False =
with_quotes self quote='"' quote_escape=quote always_quote=False =
self.clone quote_style=(Quote_Style.With_Quotes always_quote=always_quote quote=quote quote_escape=quote_escape)
## Create a clone of this with specified quoting settings.
without_quotes : Delimited
without_quotes =
without_quotes self =
self.clone quote_style=Quote_Style.No_Quotes
## Create a clone of this with first row treated as header.
with_headers : Delimited
with_headers = self.clone headers=True
with_headers self = self.clone headers=True
## Create a clone of this where the first row is treated as data, not a
header.
without_headers : Delimited
without_headers = self.clone headers=False
without_headers self = self.clone headers=False
## Create a clone of this with value parsing.
A custom `Data_Formatter` can be provided to customize parser options.
with_parsing : Data_Formatter -> Delimited
with_parsing (value_formatter=Data_Formatter) =
with_parsing self (value_formatter=Data_Formatter) =
self.clone value_formatter=value_formatter
## Create a clone of this without value parsing.
without_parsing : Delimited
without_parsing =
without_parsing self =
self.clone value_formatter=Nothing
## Creates a clone of this with a changed line ending style.
with_line_endings : Line_Ending_Style -> Delimited
with_line_endings line_endings=Infer =
with_line_endings self line_endings=Infer =
self.clone line_endings=line_endings
## Creates a clone of this with comment parsing enabled.
with_comments : Text -> Delimited
with_comments comment_character='#' =
with_comments self comment_character='#' =
self.clone comment_character=comment_character
## Creates a clone of this with comment parsing disabled.
without_comments : Delimited
without_comments =
without_comments self =
self.clone comment_character=Nothing
## A setting to infer the default behaviour of some option.
@ -212,13 +212,13 @@ type Excel
## Implements the `File.read` for this `File_Format`
read : File -> Problem_Behavior -> Any
read file on_problems =
read self file on_problems =
format = Excel.is_xls_format self.xls_format file
Excel_Module.read_excel file self.section self.headers on_problems format
## Implements the `Table.write` for this `File_Format`.
write_table : File -> Table -> Existing_File_Behavior -> Match_Columns -> Problem_Behavior -> Nothing
write_table file table on_existing_file match_columns on_problems =
write_table self file table on_existing_file match_columns on_problems =
format = Excel.is_xls_format self.xls_format file
case self.section of

View File

@ -56,6 +56,6 @@ File.read path (format=File_Format.Auto) (on_problems=Report_Warning) =
example_xls_to_table = Examples.xls.read (Excel (Sheet 'Dates'))
File.File.read : File_Format -> Problem_Behavior -> Any ! File_Error
File.File.read (format=File_Format.Auto) (on_problems=Report_Warning) =
File.File.read self (format=File_Format.Auto) (on_problems=Report_Warning) =
format.read self on_problems

View File

@ -9,27 +9,27 @@ from Standard.Table.Errors as Error_Module import Missing_Input_Columns, Column_
type Problem_Builder
type Problem_Builder oob_indices duplicate_column_selectors input_indices_already_matched missing_input_columns other
report_oob_indices indices =
report_oob_indices self indices =
append_to_ref self.oob_indices indices
report_duplicate_column_selectors selectors =
report_duplicate_column_selectors self selectors =
append_to_ref self.duplicate_column_selectors selectors
report_input_indices_already_matched indices =
report_input_indices_already_matched self indices =
append_to_ref self.input_indices_already_matched indices
report_missing_input_columns columns =
report_missing_input_columns self columns =
append_to_ref self.missing_input_columns columns
report_column_matched_by_multiple_selectors column_name selectors =
report_column_matched_by_multiple_selectors self column_name selectors =
self.report_other_warning (Column_Matched_By_Multiple_Selectors column_name selectors)
report_other_warning warning =
report_other_warning self warning =
self.other.append warning
## Returns a vector containing all reported problems, aggregated.
build_problemset : Vector
build_problemset =
build_problemset self =
problems = Vector.new_builder
build_vector_and_append ref problem_creator =
vec = ref.get . build
@ -48,14 +48,14 @@ type Problem_Builder
Any errors from the `result` take precedence over the ones owned by this
builder.
attach_problems_after : Problem_Behavior -> Any -> Any
attach_problems_after problem_behavior result =
attach_problems_after self problem_behavior result =
problem_behavior.attach_problems_after result self.build_problemset
## Attaches gathered warnings to the result of the provided computation.
If in `Report_Error` mode and there are any problems gathered, the first
one will be returned as error without even running the computation.
attach_problems_before : Problem_Behavior -> Any -> Any
attach_problems_before problem_behavior ~computation =
attach_problems_before self problem_behavior ~computation =
problem_behavior.attach_problems_before self.build_problemset computation
## PRIVATE

View File

@ -29,12 +29,12 @@ type Unique_Name_Strategy
## Vector of any duplicates renamed
renames : Vector
renames = Vector.Vector self.deduplicator.getDuplicatedNames
renames self = Vector.Vector self.deduplicator.getDuplicatedNames
## Vector of any invalid names
invalid_names : Vector
invalid_names = Vector.Vector self.deduplicator.getInvalidNames
invalid_names self = Vector.Vector self.deduplicator.getInvalidNames
## Takes a value and converts to a valid (but not necessarily unique) name
@ -48,7 +48,7 @@ type Unique_Name_Strategy
strategy.make_valid_name 1 # returns "1"
strategy.make_valid_name "Hello" # returns "Hello"
make_valid_name : Any -> Text
make_valid_name input =
make_valid_name self input =
case input of
Text -> self.deduplicator.makeValid input
Nothing -> self.make_valid_name ""
@ -65,4 +65,4 @@ type Unique_Name_Strategy
strategy.make_unique "A" # returns "A"
strategy.make_unique "A" # returns "A_1"
make_unique : Text -> Text
make_unique name = self.deduplicator.makeUnique name
make_unique self name = self.deduplicator.makeUnique name

View File

@ -32,7 +32,7 @@ type Vector_Builder
Number of elements inside of the to-be-built vector.
length : Integer
length = case self of
length self = case self of
Leaf vec -> vec.length
Append _ _ len -> len
@ -40,13 +40,13 @@ type Vector_Builder
Checks if this builder contains any elements.
is_empty : Boolean
is_empty = self.length == 0
is_empty self = self.length == 0
## PRIVATE
Materializes the actual vector from this builder.
build : Vector.Vector Any
build =
build self =
array = Array.new self.length
go ix elem = case elem of
Leaf vec ->
@ -68,7 +68,7 @@ type Vector_Builder
It returns a new builder that will yield a vector that is a concatenation
of `self` and the argument.
++ : Vector_Builder Any | Vector.Vector Any -> Vector_Builder Any
++ other = if other.is_empty then self else
++ self other = if other.is_empty then self else
len = self.length + other.length
case other of
Leaf _ -> Append self other len

View File

@ -49,7 +49,7 @@ from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Colu
headers = Examples.simple_table_json_headers
json.to_table headers
Json.Array.to_table : Vector -> Table
Json.Array.to_table fields = case self of
Json.Array.to_table self fields = case self of
Json.Array items ->
rows = items.map item-> case item of
Json.Object fs ->
@ -92,7 +92,7 @@ Json.Array.to_table fields = case self of
json = Examples.geo_json
json.to_table
Json.Object.to_table : Vector -> Table ! Invalid_Format_Error
Json.Object.to_table fields=Nothing =
Json.Object.to_table self fields=Nothing =
if self.get_type != Geo_Json.Feature_Collection.to_text then Error.throw (Invalid_Format_Error self "not being a feature collection") else
case self.get "features" of
Json.Array items ->
@ -121,5 +121,5 @@ type Invalid_Format_Error input message
Provides a human-readable representation of the Invalid_Format_Error.
Invalid_Format_Error.to_display_text : Text
Invalid_Format_Error.to_display_text =
Invalid_Format_Error.to_display_text self =
"The input " + self.input.to_text + " had an invalid format due to: " + self.message.to_text + "."

View File

@ -92,7 +92,7 @@ len_list list =
Arguments:
- act: The action to perform `self` number of times.
Number.times : List Any
Number.times act =
Number.times self act =
go = results -> number -> if number == 0 then results else
@Tail_Call go (Cons (act number) results) number-1
res = reverse_list (go Nil self)

View File

@ -35,7 +35,7 @@ type Faker
template = [l, l, n, n, n, n, n, s]
ni_number = Faker.new . string_value template
string_value : Vector -> Text
string_value template =
string_value self template =
characters = template.map possible_chars->
selected_char_ix = self.generator.nextInt possible_chars.length
possible_chars.at selected_char_ix
@ -47,7 +47,7 @@ type Faker
- length: length of text to generate
- upper_case: use upper_case letters
alpha : Integer->Boolean->Text
alpha length=1 upper_case=False =
alpha self length=1 upper_case=False =
alphabet = if upper_case then upper_case_letters else lower_case_letters
self.string_value <| 0.up_to length . map _->alphabet
@ -57,7 +57,7 @@ type Faker
- length: length of text to generate
- upper_case: use upper_case letters
alpha_numeric : Integer->Boolean->Text
alpha_numeric length=1 upper_case=False =
alpha_numeric self length=1 upper_case=False =
alphabet = (if upper_case then upper_case_letters else lower_case_letters) + numbers
self.string_value <| 0.up_to length . map _->alphabet
@ -66,23 +66,23 @@ type Faker
Arguments:
- length: length of text to generate
hexadecimal : Integer->Text
hexadecimal length=1 =
hexadecimal self length=1 =
alphabet = "0123456789ABCDEF".char_vector
self.string_value <| 0.up_to length . map _->alphabet
## Create a random Boolean value
boolean : Boolean
boolean =
boolean self =
if self.generator.nextDouble < 0.5 then True else False
## Create a random Integer value
integer : Integer->Integer->Integer
integer minimum=0 maximum=100 =
integer self minimum=0 maximum=100 =
minimum + (self.generator.nextInt (maximum - minimum))
## Create a random Decimal value
decimal : Decimal->Decimal->Decimal
decimal minimum=0.0 maximum=1.0 =
decimal self minimum=0.0 maximum=1.0 =
minimum + self.generator.nextDouble * (maximum - minimum)
## Picks an item at Random from a list
@ -91,10 +91,10 @@ type Faker
- items: Vector of items to pick from
- generator: Random number generator
vector_item : Vector->Any
vector_item items =
vector_item self items =
items.at (self.generator.nextInt items.length)
## Randomly converts some values to Nothing
make_some_nothing : Any->Decimal->Any
make_some_nothing value (chance=0.1) =
make_some_nothing self value (chance=0.1) =
if self.generator.nextDouble <= chance then Nothing else value

View File

@ -26,7 +26,7 @@ polyglot java import java.lang.StringBuilder
Suite.run_main : Any -> Nothing
Suite.run_main ~specs =
config = config_from_env
r = self.run specs config
r = Suite.run specs config
code = if r.is_fail then 1 else 0
System.exit code
@ -179,7 +179,7 @@ specify label ~behavior pending=Nothing =
- verb: The property (see `Verbs`) being asserted
- argument: The argument to the verb.
Any.should : (Verbs -> Any -> Any) -> Any -> Assertion
Any.should verb argument = verb Verbs self argument
Any.should self verb argument = verb Verbs self argument
## Fail a test with the given message.
@ -213,7 +213,7 @@ fail message =
example_should_fail_with =
Examples.throw_error . should_fail_with Examples.My_Error
Any.should_fail_with : Any -> Integer -> Assertion
Any.should_fail_with matcher frames_to_skip=0 =
Any.should_fail_with self matcher frames_to_skip=0 =
loc = Meta.get_source_location 1+frames_to_skip
fail ("Expected an error " + matcher.to_text + " but no error occurred, instead got: " + self.to_text + " (at " + loc + ").")
@ -233,7 +233,7 @@ Any.should_fail_with matcher frames_to_skip=0 =
example_should_fail_with =
Examples.throw_error . should_fail_with Examples.My_Error
Error.should_fail_with : Any -> Integer -> Assertion
Error.should_fail_with matcher frames_to_skip=0 =
Error.should_fail_with self matcher frames_to_skip=0 =
caught = self.catch
if caught.is_a matcher then Nothing else
loc = Meta.get_source_location 2+frames_to_skip
@ -280,7 +280,7 @@ expect_panic_with ~action matcher =
example_should_equal = Examples.add_1_to 1 . should_equal 2
Any.should_equal : Any -> Integer -> Assertion
Any.should_equal that frames_to_skip=0 = case self == that of
Any.should_equal self that frames_to_skip=0 = case self == that of
True -> Success
False ->
loc = Meta.get_source_location 2+frames_to_skip
@ -302,7 +302,7 @@ Any.should_equal that frames_to_skip=0 = case self == that of
example_should_not_equal = Examples.add_1_to 1 . should_not_equal 2
Any.should_not_equal : Any -> Integer -> Assertion
Any.should_not_equal that frames_to_skip=0 = case self != that of
Any.should_not_equal self that frames_to_skip=0 = case self != that of
True -> Success
False ->
loc = Meta.get_source_location 2+frames_to_skip
@ -322,7 +322,7 @@ Any.should_not_equal that frames_to_skip=0 = case self != that of
example_should_equal = Examples.add_1_to 1 . should_equal 2
Error.should_equal : Any -> Assertion
Error.should_equal _ frames_to_skip=0 = fail_match_on_unexpected_error self 1+frames_to_skip
Error.should_equal self _ frames_to_skip=0 = fail_match_on_unexpected_error self 1+frames_to_skip
## Asserts that `self` is within `epsilon` from `that`.
@ -347,7 +347,7 @@ Error.should_equal _ frames_to_skip=0 = fail_match_on_unexpected_error self 1+fr
example_should_equal =
1.00000001 . should_equal 1.00000002 epsilon=0.0001
Decimal.should_equal : Decimal -> Decimal -> Integer -> Assertion
Decimal.should_equal that epsilon=0 frames_to_skip=0 =
Decimal.should_equal self that epsilon=0 frames_to_skip=0 =
matches = case that of
Number -> self.equals that epsilon
_ -> False
@ -371,7 +371,7 @@ Decimal.should_equal that epsilon=0 frames_to_skip=0 =
"foobar".write (enso_project.data / "f.txt") . should_succeed
Any.should_succeed : Boolean -> Integer -> Any
Any.should_succeed frames_to_skip=0 =
Any.should_succeed self frames_to_skip=0 =
_ = frames_to_skip
self
@ -388,7 +388,7 @@ Any.should_succeed frames_to_skip=0 =
"foobar".write (enso_project.data / "f.txt") . should_succeed
Error.should_succeed : Boolean -> Integer -> Any
Error.should_succeed frames_to_skip=0 =
Error.should_succeed self frames_to_skip=0 =
fail_match_on_unexpected_error self 1+frames_to_skip
## Checks that the provided action returns without any errors or warnings.
@ -414,7 +414,7 @@ assert_no_problems value frames_to_skip=0 =
example_should_be_true = Examples.get_boolean . should_be_true
Boolean.should_be_true : Assertion
Boolean.should_be_true = case self of
Boolean.should_be_true self = case self of
True -> Success
False ->
loc = Meta.get_source_location 2
@ -430,7 +430,7 @@ Boolean.should_be_true = case self of
example_should_be_true = Examples.get_boolean . should_be_true
Error.should_be_true : Assertion
Error.should_be_true = fail_match_on_unexpected_error self 1
Error.should_be_true self = fail_match_on_unexpected_error self 1
## Asserts that the given `Boolean` is `False`
@ -442,7 +442,7 @@ Error.should_be_true = fail_match_on_unexpected_error self 1
example_should_be_false = Examples.get_boolean . should_be_false
Boolean.should_be_false : Assertion
Boolean.should_be_false = case self of
Boolean.should_be_false self = case self of
True ->
loc = Meta.get_source_location 2
Panic.throw (Failure "Expected True to be False (at "+loc+").")
@ -458,7 +458,7 @@ Boolean.should_be_false = case self of
example_should_be_false = Examples.get_boolean . should_be_false
Error.should_be_false : Assertion
Error.should_be_false = fail_match_on_unexpected_error self 1
Error.should_be_false self = fail_match_on_unexpected_error self 1
## Asserts that a value is of a given type.
@ -472,7 +472,7 @@ Error.should_be_false = fail_match_on_unexpected_error self 1
example_should_be_a = 1.should_be_a Boolean
Any.should_be_a : Any -> Assertion
Any.should_be_a typ = if self.is_a typ then Success else
Any.should_be_a self typ = if self.is_a typ then Success else
loc = Meta.get_source_location 0
expected_type = Meta.get_qualified_type_name typ
actual_type = Meta.get_qualified_type_name self
@ -491,7 +491,7 @@ Any.should_be_a typ = if self.is_a typ then Success else
example_should_be_an = 1.should_be_an Integer
Any.should_be_an : Any -> Assertion
Any.should_be_an typ = self.should_be_a typ
Any.should_be_an self typ = self.should_be_a typ
## Asserts that `self` value contains the same elements as `that`.
@ -515,7 +515,7 @@ Any.should_be_an typ = self.should_be_a typ
example_should_equal = [1, 2] . should_contain_the_same_elements_as [2, 1]
Any.should_contain_the_same_elements_as : Any -> Integer -> Assertion
Any.should_contain_the_same_elements_as that frames_to_skip=0 =
Any.should_contain_the_same_elements_as self that frames_to_skip=0 =
that.each element->
if self.contains element . not then
loc = Meta.get_source_location 2+frames_to_skip
@ -549,7 +549,7 @@ Any.should_contain_the_same_elements_as that frames_to_skip=0 =
example_should_equal = [1, 2] . should_contain_the_same_elements_as [2, 1]
Error.should_contain_the_same_elements_as : Any -> Assertion
Error.should_contain_the_same_elements_as _ frames_to_skip=0 = fail_match_on_unexpected_error self 1+frames_to_skip
Error.should_contain_the_same_elements_as self _ frames_to_skip=0 = fail_match_on_unexpected_error self 1+frames_to_skip
type Verbs
@ -567,7 +567,7 @@ type Verbs
- subject: The value to check. It must have a `.starts_with` method.
- argument: The expected prefix.
start_with : Text -> Text -> Assertion
start_with subject argument =
start_with self subject argument =
if subject.starts_with argument then Success else
fail (subject.to_text + " did not start with " + argument.to_text))
@ -580,7 +580,7 @@ type Verbs
- argument: The provided value to check the `subject` for equality
against.
equal : Any -> Any -> Assertion
equal subject argument =
equal self subject argument =
if subject == argument then Success else
msg = subject.to_text + " did not equal " + argument.to_text + "."
fail msg
@ -594,7 +594,7 @@ type Verbs
- argument: The provided value to check the `subject` for equality
against.
be : Any -> Any -> Assertion
be subject argument = self.equal subject argument
be self subject argument = self.equal subject argument
## PRIVATE
@ -605,7 +605,7 @@ type Verbs
This type must have a `.contains` method.
- argument: The value to see if it is contained in `subject`.
contain : Any -> Any -> Assertion
contain subject argument =
contain self subject argument =
if subject.contains argument then Success else
msg = subject.to_text + " did not contain " + argument.to_text + "."
fail msg
@ -615,13 +615,13 @@ type Verbs
type Suite_Config
type Suite_Config only_group_regexp output_path
should_run_group name =
should_run_group self name =
regexp = self.only_group_regexp
case regexp of
Text -> name.matches regexp . catch Any (_->True)
_ -> True
should_output_junit =
should_output_junit self =
self.output_path.is_nothing.not
@ -657,19 +657,19 @@ type Behavior name result
Checks if the behavior is a failure.
Behavior.is_fail : Boolean
Behavior.is_fail = self.result.is_fail
Behavior.is_fail self = self.result.is_fail
## PRIVATE
Checks if the spec group contains any failures and hence fails itself.
Spec.is_fail : Boolean
Spec.is_fail = self.behaviors.any .is_fail
Spec.is_fail self = self.behaviors.any .is_fail
## PRIVATE
Checks if the suite contains any failures, and hence fails itself.
Suite.is_fail : Boolean
Suite.is_fail = self.specs.any .is_fail
Suite.is_fail self = self.specs.any .is_fail
## PRIVATE
@ -709,7 +709,7 @@ type Assertion
Checks if the Assertion is a failure.
is_fail : Boolean
is_fail = case self of
is_fail self = case self of
Success -> False
Failure _ -> True
Pending _ -> False
@ -781,7 +781,7 @@ report_pending_group name reason config builder =
## PRIVATE
Prints a report on the tests to standard output.
Spec.print_report : Suite_Config -> (StringBuilder|Nothing) -> Nothing
Spec.print_report config builder =
Spec.print_report self config builder =
if config.should_output_junit then
builder.append (' <testsuite name="' + (escape_xml self.name) + '" timestamp="' + (Time.now.format "yyyy-MM-dd'T'HH:mm:ss") + '"')
builder.append (' tests="' + self.behaviors.length.to_text + '"')

View File

@ -12,7 +12,7 @@ import Standard.Table.Data.Table
- f: unary invokable that is applied to each vector element. Non-error
values are returned in the resulting vector. Error values are dropped.
Vector.Vector.filter_map : Any -> Vector
Vector.Vector.filter_map f = self.map f . filter .is_valid
Vector.Vector.filter_map self f = self.map f . filter .is_valid
## PRIVATE
@ -21,7 +21,7 @@ Vector.Vector.filter_map f = self.map f . filter .is_valid
Arguments:
- val: a value that will be evaluated and returned if `self` is an error.
Any.when_valid : Any -> Any
Any.when_valid ~val = self.map_valid (_-> val)
Any.when_valid self ~val = self.map_valid (_-> val)
## PRIVATE
@ -30,19 +30,19 @@ Any.when_valid ~val = self.map_valid (_-> val)
Arguments:
- val: a value that will be evaluated and returned if `self` is an error.
Error.when_valid : Any -> Any
Error.when_valid ~val = self.map_valid (_-> val)
Error.when_valid self ~val = self.map_valid (_-> val)
## PRIVATE
Checks if the value is not an error.
Any.is_valid : Any
Any.is_valid = self.is_error.not
Any.is_valid self = self.is_error.not
## PRIVATE
Checks if the value is not an error.
Error.is_valid : Any
Error.is_valid = self.is_error.not
Error.is_valid self = self.is_error.not
## PRIVATE
@ -52,7 +52,7 @@ Error.is_valid = self.is_error.not
- f: a function that will be used to generate return value from a non-error
`self` value.
Any.map_valid : Any -> Any
Any.map_valid f = f self
Any.map_valid self f = f self
## PRIVATE
@ -62,7 +62,7 @@ Any.map_valid f = f self
- _: a function that will be used to generate return value from a non-error
`self` value.
Error.map_valid : Any -> Any
Error.map_valid _ = self
Error.map_valid self _ = self
## PRIVATE
@ -73,7 +73,7 @@ Error.map_valid _ = self
Arguments:
- val: a value that will be evaluated and returned if `self` is an error.
Any.catch_ : Any -> Any
Any.catch_ ~val = self.catch Any (_-> val)
Any.catch_ self ~val = self.catch Any (_-> val)
## PRIVATE
@ -84,7 +84,7 @@ Any.catch_ ~val = self.catch Any (_-> val)
Arguments:
- val: a value that will be evaluated and returned if `self` is an error.
Error.catch_ : Any -> Any
Error.catch_ ~val = self.catch Any (_-> val)
Error.catch_ self ~val = self.catch Any (_-> val)
## PRIVATE
recover_errors : Any -> Any
@ -99,7 +99,7 @@ recover_errors ~body =
Index columns are placed before other columns.
Table.Table.all_columns : Vector
Table.Table.all_columns =
Table.Table.all_columns self =
index = self.index.catch_ []
index_columns = case index of
Vector.Vector _ -> index
@ -115,7 +115,7 @@ Table.Table.all_columns =
Arguments:
- text: the case-insensitive name of the searched column.
Table.Table.lookup_ignore_case : Text -> Column ! Nothing
Table.Table.lookup_ignore_case name =
Table.Table.lookup_ignore_case self name =
ret = self.all_columns.find <| col->
col.name.equals_ignore_case name
ret
@ -124,5 +124,5 @@ Table.Table.lookup_ignore_case name =
Checks if the column stores numbers.
Column.Column.is_numeric : Boolean
Column.Column.is_numeric =
Column.Column.is_numeric self =
[Storage.Integer,Storage.Decimal].contains self.storage_type

Some files were not shown because too many files have changed in this diff Show More