2018-09-26 00:21:47 +03:00
|
|
|
|
|
|
|
-- 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]
|
2018-11-06 01:51:59 +03:00
|
|
|
replicate n a = toSequence (take n (constant a))
|
2018-09-26 00:21:47 +03:00
|
|
|
|
|
|
|
-- 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
|
2020-02-22 02:48:12 +03:00
|
|
|
go acc a b = match at 0 a with
|
2018-09-26 00:21:47 +03:00
|
|
|
None -> acc ++ b
|
2020-02-22 02:48:12 +03:00
|
|
|
Some hd1 -> match at 0 b with
|
2018-09-26 00:21:47 +03:00
|
|
|
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
|