Skip to content

Instantly share code, notes, and snippets.

@thosakwe
Last active October 30, 2017 17:42
Show Gist options
  • Save thosakwe/37aa9ef9ea73338efdb9b44ddc7edd4f to your computer and use it in GitHub Desktop.
Save thosakwe/37aa9ef9ea73338efdb9b44ddc7edd4f to your computer and use it in GitHub Desktop.
Hypothetical strongly-typed functional language
// See, now it's starting to look presentable.
def main (
set x2 (
for n in range(1, 100) (
mul(n, 2)
)
)
set sum (
reduce x2 (fn(a:int, b:int) {
add(a, b)
})
)
print(sum)
)
// An actual switch expression. Bam.
def classify [n:int] -> string (
switch (
lt(0, n): "Negative",
eq(mod(2, n), 0): "Even Positive",
default: "Odd Positive"
)
)
def main [args: string*] (
for arg in args (
print(
classify(parse_int(arg))
)
)
)
import <dom> as $dom
def handle_click [e: $dom.Event] (
$dom.alert("Hello, world!")
)
def main (
$dom.listen (
$dom.el("#button"),
"click",
handle_click
)
)
def fib [n: int] -> int (
lte(1, n)
? n
: add(
fib(sub(n, 1)),
fib(sub(n, 2))
)
)
def main (
print(fib(13))
)
def fizz_buzz [max: int] (
loop(max, fn (i:int) {
print(run(add(i, 1), fn(n:int) {
branch([
[
and(eq(mod(3, n), 0), eq(mod(5, n), 0)),
"FizzBuzz"
],
[
eq(mod(3, n), 0),
"Fizz"
],
[
eq(mod(5, n), 0),
"Buzz"
]
])
}))
})
)
def main (
print("Hello, world!")
)
// Structs can be used for easy JSON serialization...
struct Todo (
text: string,
)
// Structs can be local, and defined within a function.
def main (
struct Foo (
status: bool,
children: Foo* = []
)
set foo (
new Foo (
status = false,
children = [
new Foo(status = true)
]
)
)
// JSON encode
set json_string print(json_encode(foo))
// Parse JSON
print(Foo(json_string))
)
// You can define a union type
type Primitive = int | double | string | bool;
// Rejects anything that is not a primitive.
def print_prim [p: Primitive] (
print(p)
)
def main (
print_prim(add(1, 3))
)
@thosakwe
Copy link
Author

thosakwe commented Aug 7, 2017

@thosakwe
Copy link
Author

thosakwe commented Oct 30, 2017

Using Shared, it's possible to share state across multiple sandboxes, using a simple mutex.

def main (
  set sum share(0)

  for i in range(1, 4) (
    fork(threadProc, [sum])
  )

  print sum.get()
)

def threadProc [sum:Shared<int>] (
  sum.set(sum.get() + 1)
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment