mirror of
https://github.com/unisonweb/unison.git
synced 2024-09-11 02:25:39 +03:00
73 lines
1.8 KiB
Plaintext
73 lines
1.8 KiB
Plaintext
|
|
-- Unison is a statically typed functional language
|
|
|
|
increment : Nat -> Nat -- signature is optional
|
|
increment n = n + 1
|
|
|
|
-- Lines starting with `>` are evaluated and printed on every file save.
|
|
> increment 99
|
|
|
|
replicate : Nat -> a -> [a]
|
|
replicate n a = toSequence (take n (constant a))
|
|
|
|
-- this is nice for quick testing!
|
|
|
|
> replicate 3 "bye"
|
|
|
|
-- can ask Unison for the type of any expression just by adding `?` to the end of it
|
|
|
|
-- > (replicate 4)?
|
|
|
|
-- here's a more interesting example, mergesort -
|
|
|
|
-- First we define the merge function, it merges two sorted lists
|
|
merge : (a -> a -> Boolean) -> [a] -> [a] -> [a]
|
|
merge lte a b =
|
|
use Sequence ++
|
|
use Optional None Some
|
|
go acc a b = match at 0 a with
|
|
None -> acc ++ b
|
|
Some hd1 -> match at 0 b with
|
|
None -> acc ++ a
|
|
Some hd2 ->
|
|
if hd1 `lte` hd2 then go (acc `snoc` hd1) (drop 1 a) b
|
|
else go (acc `snoc` hd2) a (drop 1 b)
|
|
go [] a b
|
|
|
|
-- let's make sure it works
|
|
> merge (<) [1,3,4,99,504,799] [0,19,22,23]
|
|
|
|
-- looks good, now let's write mergesort
|
|
|
|
sort : (a -> a -> Boolean) -> [a] -> [a]
|
|
sort lte a =
|
|
if Sequence.size a < 2 then a
|
|
else
|
|
l = sort lte (take (size a / 2) a)
|
|
r = sort lte (drop (size a / 2) a)
|
|
merge lte l r
|
|
|
|
-- let's make sure it works
|
|
|
|
> sort (<) [3,2,1,1,2,3,9182,1,2,34,1,80]
|
|
|
|
> sort (<) ["Dave", "Carol", "Eve", "Alice", "Bob", "Francis", "Hal", "Illy", "Joanna", "Greg", "Karen"]
|
|
|
|
-- SHIP IT!! 🚢
|
|
|
|
-- If you make a mistake, we try to have nice friendly error messages, not:
|
|
-- 🤖 ERROR DETECTED ⚡️ BEEP BOOP ⚡️ PLS RESUBMIT PROGRAM TO MAINFRAME
|
|
|
|
-- a few examples of failing programs -
|
|
|
|
--err1 =
|
|
-- a = "3"
|
|
-- sort (<) [1,2,a]
|
|
|
|
-- err1a = sort (<) "not a list"
|
|
|
|
--err2 : x -> y -> x
|
|
--err2 thing1 thing2 =
|
|
-- if true then thing1
|
|
-- else thing2
|