base¶
In [ ]:
//// test
open testing
execution¶
emit¶
In [ ]:
inl emit forall t. (x : t) : t =
$'!x '
emit_unit¶
In [ ]:
inl emit_unit forall t. (x : t) : () =
$'!x '
use¶
In [ ]:
inl use forall t. (x : t) : t =
$'use !x = !x ' : ()
$'!x '
type¶
unit¶
In [ ]:
nominal unit = $'unit'
target¶
backend_switch¶
In [ ]:
inl backend_switch forall t. x : t =
real
inl backend key : t =
inl s = real_core.string_lit_to_symbol key
real_core.record_type_try_find `(`x) s
(forall v'. => (x s) ())
(fun () => $'' : t)
!!!!BackendSwitch (
("Fsharp", backend "Fsharp"),
("Python", backend "Python"),
("Cuda", backend "Cuda")
)
target_runtime¶
In [ ]:
union target_runtime =
| Native
| Wasm
| Contract
target¶
In [ ]:
union target =
| Fsharp : target_runtime
| Cuda : target_runtime
| Rust : target_runtime
| TypeScript : target_runtime
| Python : target_runtime
run_target_args'¶
In [ ]:
inl run_target_args' forall t u. (args : u) (fn : target -> (u -> t)) : t =
backend_switch {
Fsharp = fun () =>
inl is_unit : bool =
real
typecase t with
| () => true
| _ => false
$'(* run_target_args\''
inl result = $'()' : unit
$'run_target_args\' *)'
inl emit_result x : () =
if is_unit |> not
then $'let _run_target_args\'_!result = !x '
$'\n#if FABLE_COMPILER || WASM || CONTRACT'
$'\n#if FABLE_COMPILER_RUST && \!WASM && \!CONTRACT'
inl target = Rust Native
fn target args |> emit_result
$'#endif\n#if FABLE_COMPILER_RUST && WASM'
inl target = Rust Wasm
fn target args |> emit_result
$'#endif\n#if FABLE_COMPILER_RUST && CONTRACT'
inl target = Rust Contract
fn target args |> emit_result
$'#endif\n#if FABLE_COMPILER_TYPESCRIPT'
inl target = TypeScript Native
fn target args |> emit_result
$'#endif\n#if FABLE_COMPILER_PYTHON'
inl target = Python Native
fn target args |> emit_result
$'#endif\n#if \!FABLE_COMPILER_RUST && \!FABLE_COMPILER_TYPESCRIPT && \!FABLE_COMPILER_PYTHON'
inl target = Fsharp Wasm
fn target args |> emit_result
$'#endif\n#else'
inl target = Fsharp Native
fn target args |> emit_result
$'#endif'
if is_unit
then $'// run_target_args\' is_unit'
else $'_run_target_args\'_!result ' : t
Python = fun () =>
inl target = Cuda Native
fn target args
}
run_target_args¶
In [ ]:
inl run_target_args forall t u. (args : () -> u) (fn : target -> (u -> t)) : t =
inl args = args () |> dyn
fn |> run_target_args' args
run_target¶
In [ ]:
inl run_target forall t. (fn : target -> (() -> t)) : t =
run_target_args id fn
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
run_target function
| Fsharp (Native) => fun () => $'1uy'
| Cuda (Native) => fun () => $'1'
| Rust (Native) => fun () => $'1uy'
| TypeScript (Native) => fun () => $'1uy'
| Python (Native) => fun () => $'1uy'
| _ => fun () => $'2uy'
|> _assert_eq 1u8
.py output (Cuda): __assert_eq / actual: 1 / expected: 1 .rs output: __assert_eq / actual: 1 / expected: 1 .ts output: __assert_eq / actual: 1 / expected: 1 .py output: __assert_eq / actual: 1 / expected: 1
.fsx output: __assert_eq / actual: 1uy / expected: 1uy
function¶
eval¶
In [ ]:
inl eval fn =
fn ()
flip¶
In [ ]:
inl flip fn a b =
fn b a
do¶
In [ ]:
inl do (body : () -> ()) : () =
!!!!Do (body())
indent¶
In [ ]:
inl indent (body : () -> ()) : () =
backend_switch {
Fsharp = fun () =>
inl body () =
body ()
$'(* indent' : ()
!!!!Indent (body())
$'indent *)' : ()
Python = fun () =>
!!!!Indent (body())
()
}
let'¶
In [ ]:
inl let' fn =
inl result : unit =
backend_switch {
Fsharp = fun () =>
$'()' : unit
Python = fun () =>
$'None' : unit
}
backend_switch {
Fsharp = fun () =>
$'let _let\'_!result =' : ()
fn |> indent
Python = fun () =>
$'def _let\'_!result():' : ()
fn |> indent
}
$'_let\'_!result '
exec_unit¶
In [ ]:
inl exec_unit (fn : () -> ()) : () =
backend_switch {
Fsharp = fun () =>
inl unit = $'()' : $'unit'
($'(fun () -> !fn (); !unit) ()' : $'unit') |> ignore
Python = fun () => fn ()
}
lazy¶
In [ ]:
nominal lazy t = $'Lazy<`t>'
memoize¶
In [ ]:
nominal lazy t = $'Lazy<`t>'
inl memoize forall t. (fn : () -> t) : () -> t =
inl fn = join fn
backend_switch {
Fsharp = fun () =>
inl result : lazy t = $'lazy !fn ()'
fun () => $'!result.Value' : t
Python = fun () =>
inl result = mut None
inl computed = mut false
fun () =>
if *computed
then *result
else
result <- fn () |> Some
computed <- true
*result
|> optionm.value
}
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
inl count = mut 0i32
inl add =
fun () =>
count <- *count + 1
count
|> memoize
add () |> ignore
add () |> ignore
add () |> ignore
*count
|> _assert_eq 1
.py output (Cuda): __assert_eq / actual: 1 / expected: 1 .rs output: __assert_eq / actual: 1 / expected: 1 .ts output: __assert_eq / actual: 1 / expected: 1 .py output: __assert_eq / actual: 1 / expected: 1
.fsx output: __assert_eq / actual: 1 / expected: 1
capture¶
In [ ]:
inl capture forall t. (fn : () -> t) : t =
backend_switch {
Fsharp = fun () =>
inl result = dyn true
$'let mutable _capture_!result : `t option = None '
$'('
$'(fun () ->'
$'(fun () ->'
fn () |> emit_unit
$')'
$'|> fun x -> x ()'
$') () )'
$'|> fun x -> _capture_!result <- Some x'
$'match _capture_!result with Some x -> x | None -> failwith "base.capture / _capture_!result=None"' : t
Python = fun () =>
fn ()
}
yield_from¶
In [ ]:
inl yield_from forall (t : * -> *) u. (a : t u) : () =
backend_switch {
Fsharp = fun () => $'yield\! !a ' : ()
Python = fun () => $'asyncio.run(!a())' : ()
}
join_body¶
In [ ]:
inl join_body body acc x =
if var_is x |> not
then body acc x
else
inl acc = dyn acc
join body acc x
In [ ]:
//// test
inl rec fold_list f s = function
| Cons (x, x') => fold_list f (f s x) x'
| Nil => s
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
//// print_code
[ 5i32; 4; join 3; 2; 1 ]
|> fold_list (+) 0
|> _assert_eq 15
.py output (Cuda): __assert_eq / actual: 15 / expected: 15 .rs output: __assert_eq / actual: 15 / expected: 15 .ts output: __assert_eq / actual: 15 / expected: 15 .py output: __assert_eq / actual: 15 / expected: 15
.fsx: let rec method1 () : int32 = 3 and method2 (v0 : bool) : bool = v0 and closure0 (v0 : string) () : unit = let v1 : (string -> unit) = System.Console.WriteLine v1 v0 and method0 () : unit = let v0 : int32 = method1() let v1 : int32 = 9 + v0 let v2 : int32 = v1 + 2 let v3 : int32 = v2 + 1 let v4 : bool = v3 = 15 let v6 : bool = if v4 then true else method2(v4) let v7 : string = "__assert_eq" let v8 : string = $"{v7} / actual: %A{v3} / expected: %A{15}" let v11 : unit = () let v12 : (unit -> unit) = closure0(v8) let v13 : unit = (fun () -> v12 (); v11) () let v15 : bool = v6 = false if v15 then failwith<unit> v8 method0() .rs: #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unreachable_code)] #![allow(unused_attributes)] #![allow(unused_imports)] #![allow(unused_macros)] #![allow(unused_parens)] #![allow(unused_variables)] #![allow(unused_assignments)] mod module_6ff740fe { pub mod Spiral { use super::*; use fable_library_rust::Native_::on_startup; use fable_library_rust::String_::printfn; use fable_library_rust::String_::sprintf; use fable_library_rust::String_::string; pub fn method1() -> i32 { 3_i32 } pub fn method2(v0: bool) -> bool { v0 } pub fn closure0(v0: string, unitVar: ()) { printfn!("{0}", v0); } pub fn method0() { let v3: i32 = ((9_i32 + (Spiral::method1())) + 2_i32) + 1_i32; let v4: bool = (v3) == 15_i32; let v6: bool = if v4 { true } else { Spiral::method2(v4) }; let v8: string = sprintf!( "{} / actual: {:?} / expected: {:?}", string("__assert_eq"), v3, 15_i32 ); let v13: () = { Spiral::closure0(v8.clone(), ()); () }; if (v6) == false { panic!("{}", v8,); } } // on_startup!(Spiral::method0()); } } pub use module_6ff740fe::*; pub fn main() -> Result<(), String> { Ok(Spiral::method0()) } .ts: import { int32 } from "./fable_modules/fable-library-ts.5.0.0-alpha.9/Int32.js"; import { interpolate, toText } from "./fable_modules/fable-library-ts.5.0.0-alpha.9/String.js"; export function method1(): int32 { return 3; } export function method2(v0: boolean): boolean { return v0; } export function closure0(v0: string, unitVar: void): void { console.log(v0); } export function method0(): void { const v3: int32 = (((9 + method1()) + 2) + 1) | 0; const v4: boolean = v3 === 15; const v6: boolean = v4 ? true : method2(v4); const v8: string = toText(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])); let v13: any; closure0(v8, undefined); v13 = undefined; if (v6 === false) { throw new Error(v8); } } method0(); .py: from fable_modules.fable_library.string_ import (to_text, interpolate) def method1(__unit: None=None) -> int: return 3 def method2(v0: bool) -> bool: return v0 def closure0(v0: str, unit_var: None) -> None: print(v0) def method0(__unit: None=None) -> None: v3: int = (((9 + method1()) + 2) + 1) or 0 v4: bool = v3 == 15 v6: bool = True if v4 else method2(v4) v8: str = to_text(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])) v13: None closure0(v8, None) v13 = None if v6 == False: raise Exception(v8) method0() .py (Cuda): kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp import numpy as np from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str cuda = False def method1() -> i32: return 3 def method2(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = 9 + v0 del v0 v2 = v1 + 2 del v1 v3 = v2 + 1 del v2 v4 = v3 == 15 if v4: v6 = True else: v6 = method2(v4) del v4 v9 = "__assert_eq" v10 = f"{v9} / actual: {v3} / expected: {15}" del v3, v9 print(v10) v16 = v6 == False del v6 if v16: del v16 raise Exception(v10) else: del v10, v16 return def main_body(): return method0() def main(): r = main_body() if cuda: cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .fsx output: __assert_eq / actual: 15 / expected: 15
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
//// print_code
[ 5i32; 4; join 3; 2; 1 ]
|> fold_list (join_body (+)) 0
|> _assert_eq 15
.py output (Cuda): __assert_eq / actual: 15 / expected: 15 .rs output: __assert_eq / actual: 15 / expected: 15 .ts output: __assert_eq / actual: 15 / expected: 15 .py output: __assert_eq / actual: 15 / expected: 15
.fsx: let rec method1 () : int32 = 3 and method2 (v0 : int32, v1 : int32) : int32 = let v2 : int32 = v1 + v0 v2 and method3 (v0 : bool) : bool = v0 and closure0 (v0 : string) () : unit = let v1 : (string -> unit) = System.Console.WriteLine v1 v0 and method0 () : unit = let v0 : int32 = method1() let v1 : int32 = 9 let v2 : int32 = method2(v0, v1) let v3 : int32 = v2 + 2 let v4 : int32 = v3 + 1 let v5 : bool = v4 = 15 let v7 : bool = if v5 then true else method3(v5) let v8 : string = "__assert_eq" let v9 : string = $"{v8} / actual: %A{v4} / expected: %A{15}" let v12 : unit = () let v13 : (unit -> unit) = closure0(v9) let v14 : unit = (fun () -> v13 (); v12) () let v16 : bool = v7 = false if v16 then failwith<unit> v9 method0() .rs: #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unreachable_code)] #![allow(unused_attributes)] #![allow(unused_imports)] #![allow(unused_macros)] #![allow(unused_parens)] #![allow(unused_variables)] #![allow(unused_assignments)] mod module_6ff740fe { pub mod Spiral { use super::*; use fable_library_rust::Native_::on_startup; use fable_library_rust::String_::printfn; use fable_library_rust::String_::sprintf; use fable_library_rust::String_::string; pub fn method1() -> i32 { 3_i32 } pub fn method2(v0: i32, v1: i32) -> i32 { (v1) + (v0) } pub fn method3(v0: bool) -> bool { v0 } pub fn closure0(v0: string, unitVar: ()) { printfn!("{0}", v0); } pub fn method0() { let v4: i32 = ((Spiral::method2(Spiral::method1(), 9_i32)) + 2_i32) + 1_i32; let v5: bool = (v4) == 15_i32; let v7: bool = if v5 { true } else { Spiral::method3(v5) }; let v9: string = sprintf!( "{} / actual: {:?} / expected: {:?}", string("__assert_eq"), v4, 15_i32 ); let v14: () = { Spiral::closure0(v9.clone(), ()); () }; if (v7) == false { panic!("{}", v9,); } } // on_startup!(Spiral::method0()); } } pub use module_6ff740fe::*; pub fn main() -> Result<(), String> { Ok(Spiral::method0()) } .ts: import { int32 } from "./fable_modules/fable-library-ts.5.0.0-alpha.9/Int32.js"; import { interpolate, toText } from "./fable_modules/fable-library-ts.5.0.0-alpha.9/String.js"; export function method1(): int32 { return 3; } export function method2(v0: int32, v1: int32): int32 { return v1 + v0; } export function method3(v0: boolean): boolean { return v0; } export function closure0(v0: string, unitVar: void): void { console.log(v0); } export function method0(): void { const v4: int32 = ((method2(method1(), 9) + 2) + 1) | 0; const v5: boolean = v4 === 15; const v7: boolean = v5 ? true : method3(v5); const v9: string = toText(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v4, 15])); let v14: any; closure0(v9, undefined); v14 = undefined; if (v7 === false) { throw new Error(v9); } } method0(); .py: from fable_modules.fable_library.string_ import (to_text, interpolate) def method1(__unit: None=None) -> int: return 3 def method2(v0: int, v1: int) -> int: return v1 + v0 def method3(v0: bool) -> bool: return v0 def closure0(v0: str, unit_var: None) -> None: print(v0) def method0(__unit: None=None) -> None: v4: int = ((method2(method1(), 9) + 2) + 1) or 0 v5: bool = v4 == 15 v7: bool = True if v5 else method3(v5) v9: str = to_text(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v4, 15])) v14: None closure0(v9, None) v14 = None if v7 == False: raise Exception(v9) method0() .py (Cuda): kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp import numpy as np from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str cuda = False def method1() -> i32: return 3 def method2(v0 : i32, v1 : i32) -> i32: v2 = v1 + v0 del v0, v1 return v2 def method3(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = 9 v2 = method2(v0, v1) del v0, v1 v3 = v2 + 2 del v2 v4 = v3 + 1 del v3 v5 = v4 == 15 if v5: v7 = True else: v7 = method3(v5) del v5 v10 = "__assert_eq" v11 = f"{v10} / actual: {v4} / expected: {15}" del v4, v10 print(v11) v17 = v7 == False del v7 if v17: del v17 raise Exception(v11) else: del v11, v17 return def main_body(): return method0() def main(): r = main_body() if cuda: cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .fsx output: __assert_eq / actual: 15 / expected: 15
join_body_unit¶
In [ ]:
inl join_body_unit body d x =
if var_is d |> not
then body x
else
inl x = dyn x
join body x
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
//// print_code
[ 5i32; 4; join 3; 2; 1 ]
|> fold_list (fun acc n => join_body_unit ((+) acc) n n) 0
|> _assert_eq 15
.py output (Cuda): __assert_eq / actual: 15 / expected: 15 .rs output: __assert_eq / actual: 15 / expected: 15 .ts output: __assert_eq / actual: 15 / expected: 15 .py output: __assert_eq / actual: 15 / expected: 15
.fsx: let rec method1 () : int32 = 3 and method2 (v0 : int32) : int32 = let v1 : int32 = 9 + v0 v1 and method3 (v0 : bool) : bool = v0 and closure0 (v0 : string) () : unit = let v1 : (string -> unit) = System.Console.WriteLine v1 v0 and method0 () : unit = let v0 : int32 = method1() let v1 : int32 = method2(v0) let v2 : int32 = v1 + 2 let v3 : int32 = v2 + 1 let v4 : bool = v3 = 15 let v6 : bool = if v4 then true else method3(v4) let v7 : string = "__assert_eq" let v8 : string = $"{v7} / actual: %A{v3} / expected: %A{15}" let v11 : unit = () let v12 : (unit -> unit) = closure0(v8) let v13 : unit = (fun () -> v12 (); v11) () let v15 : bool = v6 = false if v15 then failwith<unit> v8 method0() .rs: #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unreachable_code)] #![allow(unused_attributes)] #![allow(unused_imports)] #![allow(unused_macros)] #![allow(unused_parens)] #![allow(unused_variables)] #![allow(unused_assignments)] mod module_6ff740fe { pub mod Spiral { use super::*; use fable_library_rust::Native_::on_startup; use fable_library_rust::String_::printfn; use fable_library_rust::String_::sprintf; use fable_library_rust::String_::string; pub fn method1() -> i32 { 3_i32 } pub fn method2(v0: i32) -> i32 { 9_i32 + (v0) } pub fn method3(v0: bool) -> bool { v0 } pub fn closure0(v0: string, unitVar: ()) { printfn!("{0}", v0); } pub fn method0() { let v3: i32 = ((Spiral::method2(Spiral::method1())) + 2_i32) + 1_i32; let v4: bool = (v3) == 15_i32; let v6: bool = if v4 { true } else { Spiral::method3(v4) }; let v8: string = sprintf!( "{} / actual: {:?} / expected: {:?}", string("__assert_eq"), v3, 15_i32 ); let v13: () = { Spiral::closure0(v8.clone(), ()); () }; if (v6) == false { panic!("{}", v8,); } } // on_startup!(Spiral::method0()); } } pub use module_6ff740fe::*; pub fn main() -> Result<(), String> { Ok(Spiral::method0()) } .ts: import { int32 } from "./fable_modules/fable-library-ts.5.0.0-alpha.9/Int32.js"; import { interpolate, toText } from "./fable_modules/fable-library-ts.5.0.0-alpha.9/String.js"; export function method1(): int32 { return 3; } export function method2(v0: int32): int32 { return 9 + v0; } export function method3(v0: boolean): boolean { return v0; } export function closure0(v0: string, unitVar: void): void { console.log(v0); } export function method0(): void { const v3: int32 = ((method2(method1()) + 2) + 1) | 0; const v4: boolean = v3 === 15; const v6: boolean = v4 ? true : method3(v4); const v8: string = toText(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])); let v13: any; closure0(v8, undefined); v13 = undefined; if (v6 === false) { throw new Error(v8); } } method0(); .py: from fable_modules.fable_library.string_ import (to_text, interpolate) def method1(__unit: None=None) -> int: return 3 def method2(v0: int) -> int: return 9 + v0 def method3(v0: bool) -> bool: return v0 def closure0(v0: str, unit_var: None) -> None: print(v0) def method0(__unit: None=None) -> None: v3: int = ((method2(method1()) + 2) + 1) or 0 v4: bool = v3 == 15 v6: bool = True if v4 else method3(v4) v8: str = to_text(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])) v13: None closure0(v8, None) v13 = None if v6 == False: raise Exception(v8) method0() .py (Cuda): kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp import numpy as np from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str cuda = False def method1() -> i32: return 3 def method2(v0 : i32) -> i32: v1 = 9 + v0 del v0 return v1 def method3(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = method2(v0) del v0 v2 = v1 + 2 del v1 v3 = v2 + 1 del v2 v4 = v3 == 15 if v4: v6 = True else: v6 = method3(v4) del v4 v9 = "__assert_eq" v10 = f"{v9} / actual: {v3} / expected: {15}" del v3, v9 print(v10) v16 = v6 == False del v6 if v16: del v16 raise Exception(v10) else: del v10, v16 return def main_body(): return method0() def main(): r = main_body() if cuda: cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .fsx output: __assert_eq / actual: 15 / expected: 15
arithmetic¶
(+.)¶
In [ ]:
inl (+.) forall t. (a : t) (b : t) : t =
$'!a + !b '
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'3' : i32) +. ($'-6' : i32)
|> _assert_eq -3i32
.py output (Cuda): __assert_eq / actual: -3 / expected: -3 .rs output: __assert_eq / actual: -3 / expected: -3 .ts output: __assert_eq / actual: -3 / expected: -3 .py output: __assert_eq / actual: -3 / expected: -3
.fsx output: __assert_eq / actual: -3 / expected: -3
(-.)¶
In [ ]:
inl (-.) forall t. (a : t) (b : t) : t =
$'!a - !b '
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'3' : i32) -. ($'6' : i32)
|> _assert_eq -3i32
.py output (Cuda): __assert_eq / actual: -3 / expected: -3 .rs output: __assert_eq / actual: -3 / expected: -3 .ts output: __assert_eq / actual: -3 / expected: -3 .py output: __assert_eq / actual: -3 / expected: -3
.fsx output: __assert_eq / actual: -3 / expected: -3
(*.)¶
In [ ]:
inl (*.) forall t. (a : t) (b : t) : t =
$'!a * !b '
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'3' : i32) *. ($'-1' : i32)
|> _assert_eq -3i32
.py output (Cuda): __assert_eq / actual: -3 / expected: -3 .rs output: __assert_eq / actual: -3 / expected: -3 .ts output: __assert_eq / actual: -3 / expected: -3 .py output: __assert_eq / actual: -3 / expected: -3
.fsx output: __assert_eq / actual: -3 / expected: -3
(/.)¶
In [ ]:
inl (/.) forall t. (a : t) (b : t) : t =
$'!a / !b '
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'-3' : i32) /. ($'1' : i32)
|> _assert_eq -3i32
.py output (Cuda): __assert_eq / actual: -3.0 / expected: -3 .rs output: __assert_eq / actual: -3 / expected: -3 .ts output: __assert_eq / actual: -3 / expected: -3 .py output: __assert_eq / actual: -3 / expected: -3
.fsx output: __assert_eq / actual: -3 / expected: -3
comparison¶
(=.)¶
In [ ]:
inl (=.) forall t. (a : t) (b : t) : bool =
backend_switch {
Fsharp = fun () => $'!a = !b ' : bool
Python = fun () => $'!a == !b ' : bool
}
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'-3' : i32) =. ($'-3' : i32)
|> _assert_eq true
.py output (Cuda): __assert_eq / actual: True / expected: True .rs output: __assert_eq / actual: true / expected: true .ts output: __assert_eq / actual: true / expected: true .py output: __assert_eq / actual: true / expected: true
.fsx output: __assert_eq / actual: true / expected: true
(<>.)¶
In [ ]:
inl (<>.) forall t. (a : t) (b : t) : bool =
backend_switch {
Fsharp = fun () => $'!a <> !b ' : bool
Python = fun () => $'!a \!= !b ' : bool
}
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'-3' : i32) <>. ($'3' : i32)
|> _assert_eq true
.py output (Cuda): __assert_eq / actual: True / expected: True .rs output: __assert_eq / actual: true / expected: true .ts output: __assert_eq / actual: true / expected: true .py output: __assert_eq / actual: true / expected: true
.fsx output: __assert_eq / actual: true / expected: true
(<>..)¶
In [ ]:
inl (<>..) a b =
fun () => a = b
|> dyn
|> eval
|> not
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
($'-3' : i32) <>.. ($'3' : i32)
|> _assert_eq true
.py output (Cuda): __assert_eq / actual: True / expected: True .rs output: __assert_eq / actual: true / expected: true .ts output: __assert_eq / actual: true / expected: true .py output: __assert_eq / actual: true / expected: true
.fsx output: __assert_eq / actual: true / expected: true
composition¶
append¶
In [ ]:
prototype append t : t -> t -> t
(++)¶
In [ ]:
inl (++) a b =
b |> append a
pair¶
pair¶
In [ ]:
nominal pair a b = $'(`a * `b)'
inl pair x y =
x, y
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
pair 1i32 2i32
|> _assert_eq (1, 2)
.py output (Cuda): __assert_eq / actual: (1, 2) / expected: (1, 2) .rs output: __assert_eq / actual: (1, 2) / expected: (1, 2) .ts output: __assert_eq / actual: 1,2 / expected: 1,2 .py output: __assert_eq / actual: (1, 2) / expected: (1, 2)
.fsx output: __assert_eq / actual: struct (1, 2) / expected: struct (1, 2)
new_pair¶
In [ ]:
inl new_pair forall a b. (a : a) (b : b) : pair a b =
$'!a, !b '
from_pair¶
In [ ]:
inl from_pair forall a b. (pair : pair a b) : a * b =
backend_switch {
Fsharp = fun () =>
$'let (a, b) = !pair '
($'a' : a), ($'b' : b)
Python = fun () =>
$'a, b = !pair '
($'a' : a), ($'b' : b)
}
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
new_pair "a" (new_pair 1i32 "b")
|> from_pair
|> _assert_eq' ("a", (new_pair 1i32 "b"))
.py output (Cuda): __assert_eq' / actual: ('a', (1, 'b')) / expected: ('a', (1, 'b')) .rs output: __assert_eq' / actual: ("a", (1, "b")) / expected: ("a", (1, "b")) .ts output: __assert_eq' / actual: a,1,b / expected: a,1,b .py output: __assert_eq' / actual: ('a', (1, 'b')) / expected: ('a', (1, 'b'))
.fsx output: __assert_eq' / actual: struct ("a", (1, "b")) / expected: struct ("a", (1, "b"))
application¶
(||>)¶
In [ ]:
inl (||>) (arg1, arg2) fn =
arg2 |> fn arg1
(||>)¶
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
(3i32, 2i32)
||> fun a b => a - b
|> _assert_eq 1
.py output (Cuda): __assert_eq / actual: 1 / expected: 1 .rs output: __assert_eq / actual: 1 / expected: 1 .ts output: __assert_eq / actual: 1 / expected: 1 .py output: __assert_eq / actual: 1 / expected: 1
.fsx output: __assert_eq / actual: 1 / expected: 1
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
(1i32, 2i32)
||> flip pair
|> _assert_eq (2, 1)
.py output (Cuda): __assert_eq / actual: (2, 1) / expected: (2, 1) .rs output: __assert_eq / actual: (2, 1) / expected: (2, 1) .ts output: __assert_eq / actual: 2,1 / expected: 2,1 .py output: __assert_eq / actual: (2, 1) / expected: (2, 1)
.fsx output: __assert_eq / actual: struct (2, 1) / expected: struct (2, 1)
fix_condition¶
In [ ]:
inl fix_condition x a b =
if x ()
then a () |> fun x => $'(* fix_condition then' : ()
else
$'fix_condition then *) else' : ()
b () |> fun x => $'(* fix_condition else' : ()
|> fun x => $'fix_condition else *)' : ()
type¶
infer¶
In [ ]:
nominal infer = $'_'
infer'¶
In [ ]:
nominal infer' t = $'_'
any¶
In [ ]:
nominal any = $'obj'
null¶
In [ ]:
inl null forall t. () : t =
backend_switch {
Fsharp = fun () => $'null |> unbox<`t>' : t
Python = fun () => $'None' : t
}
defaultof¶
In [ ]:
inl defaultof forall t. () : t =
$'Unchecked.defaultof<`t>'
choice2'¶
In [ ]:
nominal choice2' a b = $'Choice<`a, `b>'
choice2_unbox¶
In [ ]:
inl choice2_unbox forall t1 t2. (choice : choice2' t1 t2) : choice2 t1 t2 =
run_target_args (fun () => choice) function
| Fsharp _ => fun choice =>
inl c1of2 (x : t1) : _ _ t2 = C1of2 x
inl c2of2 (x : t2) : _ t1 _ = C2of2 x
inl c1of2 = join c1of2
inl c2of2 = join c2of2
$'match !choice with Choice1Of2 x -> !c1of2 x | Choice2Of2 x -> !c2of2 x'
| _ => fun _ => null ()
ref¶
ref¶
In [ ]:
nominal ref t = $'`t ref'
new_ref¶
In [ ]:
inl new_ref forall t. (x : t) : ref t =
$'ref !x '
ref_value¶
In [ ]:
inl ref_value forall t. (x : ref t) : t =
$'!x.Value'
ref_set_value¶
In [ ]:
inl ref_set_value forall t. (value : t) (ref : ref t) : ref t =
$'!ref.Value <- !value '
ref
convert¶
to¶
In [ ]:
inl to forall t u. (x : t) : u =
$'!x ' : u
convert¶
In [ ]:
inl convert forall t u. (x : t) : u =
backend_switch {
Fsharp = fun () => $'!x |> `u ' : u
Python = fun () => $'`u(!x)' : u
}
unbox¶
In [ ]:
inl unbox forall t u. (x : t) : u =
backend_switch {
Fsharp = fun () => $'!x |> unbox<`u>' : u
Python = fun () => x |> to : u
}
u8¶
In [ ]:
inl u8 forall t. (x : t) : u8 =
backend_switch {
Fsharp = fun () => x |> $'uint8' : u8
Python = fun () => x |> to : u8
}
u16¶
In [ ]:
inl u16 forall t. (x : t) : u16 =
backend_switch {
Fsharp = fun () => x |> $'uint16' : u16
Python = fun () => $'!x & 0xFFFF' : u16
}
u64¶
In [ ]:
inl u64 forall t. (x : t) : u64 =
backend_switch {
Fsharp = fun () => x |> $'uint64' : u64
Python = fun () => x |> to : u64
}
i32¶
In [ ]:
inl i32 forall t. (x : t) : i32 =
backend_switch {
Fsharp = fun () => x |> convert : i32
Python = fun () => x |> convert : i32
}
i64¶
In [ ]:
inl i64 forall t. (x : t) : i64 =
backend_switch {
Fsharp = fun () => x |> $'int64' : i64
Python = fun () => x |> to : i64
}
f32¶
In [ ]:
inl f32 forall t. (x : t) : f32 =
backend_switch {
Fsharp = fun () => x |> $'float32' : f32
Python = fun () => x |> to : f32
}
f64¶
In [ ]:
inl f64 forall t. (x : t) : f64 =
backend_switch {
Fsharp = fun () => x |> $'float' : f64
Python = fun () => x |> to : f64
}
unativeint¶
In [ ]:
nominal unativeint = $'unativeint'
convert_i32¶
In [ ]:
inl convert_i32 forall t. (x : t) : i32 =
backend_switch {
Fsharp = fun () => x |> $'System.Convert.ToInt32' : i32
Python = fun () => x |> to : i32
}
convert_i32_base¶
In [ ]:
inl convert_i32_base forall t. (base : i32) (x : t) : i32 =
backend_switch {
Fsharp = fun () => $'System.Convert.ToInt32 (!x, !base)' : i32
Python = fun () => $'int (!x, !base)' : i32
}
(:>)¶
In [ ]:
prototype (~:>) r : forall t. t -> r
to_any¶
In [ ]:
inl to_any forall t. (obj : t) : any =
obj |> to
(~:>) any¶
In [ ]:
instance (~:>) any = to_any
error¶
exn¶
In [ ]:
nominal exn = $"backend_switch `({ Fsharp : $'exn'; Python : $'BaseException' })"
inl exn x =
x |> $'`exn '
try¶
In [ ]:
inl try forall t. (fn : () -> t) (ex_fn : exn -> option t) : option t =
inl some x : option t = Some x
inl some = dyn some
inl fn = dyn fn
inl ex_fn = dyn ex_fn
backend_switch {
Fsharp = fun () =>
$'let result = ref !(None : option t)'
$'try'
$' result.Value <- !fn () |> !some '
$'with ex ->'
$' result.Value <- !ex_fn ex '
$'result.Value' : option t
Python = fun () =>
$'result = !(None : option t)'
inl fn = dyn fn
inl ex_fn = dyn ex_fn
$'try:'
$' result = !some(!fn())\n \'\'\''
$'\'\'\''
$'except Exception as e:'
$' result = !ex_fn(e)'
$'result' : option t
}
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
try
fun () => a ;[ 0i32 ] |> am'.index 1i32 |> sm'.format
(fun ex => $'!ex ' |> sm'.format_exception |> Some)
|> optionm.value
|> _assert_eq (run_target function
| Fsharp => fun () => join "System.IndexOutOfRangeException: Index was outside the bounds of the array."
| Cuda => fun () => "index 1 is out of bounds for axis 0 with size 1"
| Rust => fun () => "Exception { message: \"index out of bounds: the len is 1 but the index is 1\" }"
| TypeScript => fun () => "Error: Index was outside the bounds of the array.\\nParameter name: index"
| Python => fun () => "array index out of range"
)
.py output (Cuda): __assert_eq / actual: index 1 is out of bounds for axis 0 with size 1 / expected: index 1 is out of bounds for axis 0 with size 1 .rs output: __assert_eq / actual: "Exception { message: "index out of bounds: the len is 1 but the index is 1" }" / expected: "Exception { message: "index out of bounds: the len is 1 but the index is 1" }" .ts output: __assert_eq / actual: Error: Index was outside the bounds of the array.\nParameter name: index / expected: Error: Index was outside the bounds of the array.\nParameter name: index .py output: __assert_eq / actual: array index out of range / expected: array index out of range
.fsx output: __assert_eq / actual: "System.IndexOutOfRangeException: Index was outside the bounds of the array." / expected: "System.IndexOutOfRangeException: Index was outside the bounds of the array."
try_unit¶
In [ ]:
inl try_unit forall t. (fn : () -> ()) (ex_fn : (() -> exn) -> ()) : t =
backend_switch {
Fsharp = fun () => $'try' : ()
Python = fun () => $'try:' : ()
}
fn |> indent
backend_switch {
Fsharp = fun () => $'with ex ->' : ()
Python = fun () => $'except Exception as ex:' : ()
}
fun () =>
inl ex = $'ex'
inl ex () =
ex
ex_fn ex
|> indent
backend_switch {
Fsharp = fun () =>
$'(* try_unit'
$'try_unit *)' : t
Python = fun () => $'' : t
}
try_unit'¶
In [ ]:
inl try_unit' forall t. (ex_fn : (() -> exn) -> ()) (fn : () -> ()) : t =
try_unit fn ex_fn
try_finally¶
In [ ]:
inl try_finally forall t. (fn : () -> ()) (finally : () -> ()) : t =
backend_switch {
Fsharp = fun () => $'try' : ()
Python = fun () => $'try:' : ()
}
fn |> indent
backend_switch {
Fsharp = fun () => $'finally' : ()
Python = fun () => $'finally:' : ()
}
finally |> indent
backend_switch {
Fsharp = fun () =>
$'(* try_finally'
$'try_finally *)'
()
Python = fun () => ()
}