<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Bluishcoder</title>
 <link href="http://bluishcoder.co.nz/atom.xml" rel="self"/>
 <link href="http://bluishcoder.co.nz/"/>
 <updated>2024-02-02T22:54:17+13:00</updated>
 <id>http://bluishcoder.co.nz/</id>
 <author>
   <name>Bluishcoder</name>
   <email>admin@bluishcoder.co.nz</email>
 </author>

 
 <entry>
   <title>Fun Factor Libraries</title>
   <link href="http://bluishcoder.co.nz/2020/04/18/fun-factor-libraries.html"/>
   <updated>2020-04-18T23:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2020/04/18/fun-factor-libraries</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;https://factorcode.org/&quot;&gt;Factor&lt;/a&gt; is a programming language I&#39;ve &lt;a href=&quot;http://bluishcoder.co.nz/tags/factor/&quot;&gt;written about before&lt;/a&gt; and in the early days of Factor development I wrote a number of libraries and contributed to development. It&#39;s been a while since I&#39;ve contributed but I still use Factor. The development environment has a very Smalltalk-like feel to it and it includes full documentation and browseable source code of libraries.&lt;/p&gt;

&lt;p&gt;This post isn&#39;t about Factor the language, but is about some of the neat fun libraries that people have written that shows off the graphical development system a bit.&lt;/p&gt;

&lt;h2&gt;Minesweeper&lt;/h2&gt;

&lt;p&gt;The first example is an implementation of the game Minesweeper in Factor. A &lt;a href=&quot;https://re-factor.blogspot.com/2018/02/minesweeper.html&quot;&gt;blog post by the author&lt;/a&gt; explains the implementation. To run it inside Factor, do the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;minesweeper&quot; run
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A new window will open showing the game. Help can be shown with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;minesweeper&quot; help
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;http://bluishcoder.co.nz/factor/factor_minesweeper.gif&quot;&gt;&lt;/p&gt;

&lt;h2&gt;XKCD&lt;/h2&gt;

&lt;p&gt;Another fun example is displaying XKCD comics inside the Factor REPL. The &lt;a href=&quot;http://re-factor.blogspot.com/2011/04/xkcd.html&quot;&gt;implementation is explained by the author here&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;USE: xkcd
latest-xkcd.
...comic displayed here...
random-xkcd.
...comic displayed here...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;http://bluishcoder.co.nz/factor/factor_xkcd.gif&quot;&gt;&lt;/p&gt;

&lt;h2&gt;Wikipedia&lt;/h2&gt;

&lt;p&gt;If it seems like all the examples I&#39;m using are from the excellent re-factor blog - well, most of them are. This blog post from re-factor &lt;a href=&quot;https://re-factor.blogspot.com/2012/12/today-in-history.html&quot;&gt;shows pulling historical facts from Wikipedia&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;USE: wikipedia
USE: calendar

today historical-events.
...a list of historical events from wikipedia for today...

yesterday historical-births.
...a list of historical births from wikipedia for yesterday...

5 weeks ago historical-deaths.
...a list of historical deaths from wikipedia for five weeks ago...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The items in the list are graphical elements that can be manipulated. Left clicking on the coloured words will open a URL in the default web browser. Right clicking allows you to push the element on the Factor stack and manipulate it.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;https://docs.factorcode.org/content/article-calendar.html&quot;&gt;calendar vocab&lt;/a&gt; has a lot of interesting words that allow doing calculations like &quot;5 weeks ago&quot;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://bluishcoder.co.nz/factor/factor_wikipedia.gif&quot;&gt;&lt;/p&gt;

&lt;h2&gt;Hacker News&lt;/h2&gt;

&lt;p&gt;There&#39;s a &lt;a href=&quot;https://docs.factorcode.org/content/vocab-hacker-news.html&quot;&gt;hacker-news&lt;/a&gt; vocabulary that provides words to list current articles on the &lt;a href=&quot;https://news.ycombinator.com/&quot;&gt;Hacker News&lt;/a&gt; website. Like the previous Wikipedia example, the graphical elements are clickable objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;USE: hacker-news

hacker-news-top.
...list of top articles...

hacker-news-show.
...list articles related to showing projects...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;http://bluishcoder.co.nz/factor/factor_hackernews.gif&quot;&gt;&lt;/p&gt;

&lt;h2&gt;CPU 8080 Emulator&lt;/h2&gt;

&lt;p&gt;A number of years ago I wrote a CPU 8080 emulator in Factor and used this to implement a &lt;a href=&quot;http://bluishcoder.co.nz/2007/05/12/factor-space-invaders-updated.html&quot;&gt;Space Invaders Emulator&lt;/a&gt; and then emulators for a couple of other 8080 arcade games, Balloon Bomber and Lunar Rescue. These examples require the original arcade ROMs and instructions for using them are in the online help:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;rom.space-invaders&quot; run
...opens in a new window...
&quot;rom.balloon-bomber&quot; run
...opens in a new window...
&quot;rom.lunar-rescue&quot; run
...opens in a new window...

&quot;rom.space-invaders&quot; help
...displays help...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;http://bluishcoder.co.nz/factor/factor_cpu8080.gif&quot;&gt;&lt;/p&gt;

&lt;h2&gt;Gopher Implementation&lt;/h2&gt;

&lt;p&gt;Another magical implementation from the re-factor blog, a &lt;a href=&quot;https://re-factor.blogspot.com/2016/10/gopher-server.html&quot;&gt;Gopher server&lt;/a&gt; and a &lt;a href=&quot;http://re-factor.blogspot.com/2014/12/gopher.html&quot;&gt;graphical Gopher Client&lt;/a&gt;. This is a video I made of the gopher client on YouTube:&lt;/p&gt;

&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/YoHkx9aICaQ&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt;


&lt;p&gt;I also did a video that shows some Factor development tools on the running Gopher client to show how everything is live in Factor:&lt;/p&gt;

&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/sozwQ7QmOhs&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt;


&lt;h2&gt;And More&lt;/h2&gt;

&lt;p&gt;There&#39;s much more buried inside Factor. The &lt;a href=&quot;https://docs.factorcode.org/content/article-handbook-library-reference.html&quot;&gt;list of articles&lt;/a&gt; and &lt;a href=&quot;https://docs.factorcode.org/content/article-vocab-index.html&quot;&gt;list of vocabularies&lt;/a&gt; from the online help is a good way to explore. This help system is also available offline in a Factor install. By default many libraries aren&#39;t loaded when Factor starts but you can force loading everything using &lt;code&gt;load-all&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;load-all
...all vocabs are loaded - prepare to wait for a while...
save
...saves the image so when factor is restarted the vocabs remain loaded...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The benefit of doing this while developing is all the online help, source and words are available via the inbuilt tools like &quot;apropos&quot;, &quot;usage&quot;, etc.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Defining Types in Shen</title>
   <link href="http://bluishcoder.co.nz/2019/10/03/defining-types-in-shen.html"/>
   <updated>2019-10-03T18:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2019/10/03/defining-types-in-shen</id>
   <content type="html">&lt;p&gt;The &lt;a href=&quot;http://shenlanguage.org/&quot;&gt;Shen programming language&lt;/a&gt; has an extensible type system. Types are defined using &lt;a href=&quot;https://en.wikipedia.org/wiki/Sequent_calculus&quot;&gt;sequent calculus&lt;/a&gt; and the system is powerful enough to create a variety of exotic types but it can be difficult when first starting with Shen to know how to use that power. In this post I hope to go through some basic examples of defining types in Shen without needing to know too much sequent calculus details.&lt;/p&gt;

&lt;p&gt;For an overview of Shen there is &lt;a href=&quot;http://www.shenlanguage.org/learn-shen/shen_in_15mins.html&quot;&gt;Shen in 15 minutes&lt;/a&gt; and the &lt;a href=&quot;http://www.shenlanguage.org/learn-shen/OSmanual.htm&quot;&gt;Shen OS Kernel Manual&lt;/a&gt;. An &lt;a href=&quot;https://gravicappa.github.io/shen-js/shen.html#.doc/welcome.html&quot;&gt;interactive JavaScript REPL&lt;/a&gt; exists to try examples in the browser or pick on one of the &lt;a href=&quot;https://shen-language.github.io/&quot;&gt;existing Shen language ports&lt;/a&gt;. For these examples I&#39;m using my &lt;a href=&quot;https://github.com/doublec/shen-wasp/&quot;&gt;Wasp Lisp port of Shen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Shen is optionally typed. The type checker can be turned off and on. By default it is off and this can be seen in the Shen prompt by the presence of a &#39;&lt;code&gt;-&lt;/code&gt;&#39; character:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(0-) ...shen code...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Turning type checking on is done by using &lt;code&gt;(tc +)&lt;/code&gt;. The &#39;&lt;code&gt;-&lt;/code&gt;&#39; in the prompt changes to a &#39;&lt;code&gt;+&lt;/code&gt;&#39; to show type checking is active. It can be turned off again with &lt;code&gt;(tc -)&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(0-) (tc +)
(1+) (tc -)
(2-) ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Types in Shen are defined using &lt;code&gt;datatype&lt;/code&gt;. The body of the &lt;code&gt;datatype&lt;/code&gt; definition contains a series of sequent calculus rules. These rules define how an object in Shen can be proved to belong to a particular type. Rather than go through a detailed description of sequent calculus, I&#39;m going to present common examples of types in Shen to learn by example and dive into details as needed. There&#39;s the &lt;a href=&quot;https://www.amazon.co.uk/Book-Shen-Third-Mark-Tarver/dp/1784562130&quot;&gt;Shen Language Book&lt;/a&gt; for much more detail if needed.&lt;/p&gt;

&lt;h2&gt;Records&lt;/h2&gt;

&lt;p&gt;One way of storing collections of data in Shen is to use lists or vectors. For example, given an the concept of a &#39;person&#39; that has a name and age, this can be stored in a list with functions to get the relevent data:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(tc -)

(define make-person
  Name Age -&amp;gt; [Name Age])

(define get-name
  [Name Age] -&amp;gt; Name)

(define get-age
  [Name Age] -&amp;gt; Age)

(get-age (make-person &quot;Person1&quot; 42))
 =&amp;gt; 42
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the typed subset of Shen we can define a type for this person object using &lt;code&gt;datatype&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype person
  N : string; A : number;
  _______________________
  [N A] : person;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This defines one sequent calculus rule. The way to read it is starting with the code below the underscore line, followed by the code above it. In this case the rule states that if an expression matching the pattern &lt;code&gt;[N A]&lt;/code&gt; is encountered, where &lt;code&gt;N&lt;/code&gt; is a &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;A&lt;/code&gt; is a number, then type that expression as &lt;code&gt;person&lt;/code&gt;. With that rule defined, we can ask Shen if lists are of the type &lt;code&gt;person&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(0+) [&quot;Person&quot; 42] : person
[&quot;Person1&quot; 42] : person

(1+) [&quot;Person1&quot; &quot;Person1&quot;] : person
[error shen &quot;type error&quot;]

(2+) [&quot;Person 42&quot;]
[&quot;Person1&quot; 42] : person
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Given this &lt;code&gt;person&lt;/code&gt; type, we might write a &lt;code&gt;get-age&lt;/code&gt; function that is typed such that it only works on &lt;code&gt;person&lt;/code&gt; objects as follows (The &lt;code&gt;{ ...}&lt;/code&gt; syntax in function definitions provides the expected type of the function):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define get-age
  { person --&amp;gt; number }
  [N A] -&amp;gt; A)
[error shen &quot;type error in rule 1 of get-age&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Shen rejects this definition as not being type safe. The reason for this is because our &lt;code&gt;datatype&lt;/code&gt; definition only states that &lt;code&gt;[N A]&lt;/code&gt; is a &lt;code&gt;person&lt;/code&gt; if &lt;code&gt;N&lt;/code&gt; is a &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;A&lt;/code&gt; is a &lt;code&gt;number&lt;/code&gt;. It does not state that a &lt;code&gt;person&lt;/code&gt; object is constructed only of a &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;number&lt;/code&gt;. For example, we could have an additional definition as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype person2
  N : string; A : string;
  _______________________
  [N A] : person;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can create different types of &lt;code&gt;person&lt;/code&gt; objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(0+) [&quot;Person&quot; 42 ] : person
[&quot;Person&quot; 42] : person

(1+) [&quot;Person&quot; &quot;young&quot;] : person
[&quot;Person&quot; &quot;young&quot;] : person
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;get-age&lt;/code&gt; is obviously badly typed in the presence of this additional type of &lt;code&gt;person&lt;/code&gt; which is why Shen rejected it originally. To resolve this we need to tell Shen that an &lt;code&gt;[N A]&lt;/code&gt; is a &lt;code&gt;person&lt;/code&gt; if and only if &lt;code&gt;N&lt;/code&gt; is a &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;A&lt;/code&gt; is a &lt;code&gt;person&lt;/code&gt;. This is done with what is called a &#39;left rule&#39;. Such a rule defines how a &lt;code&gt;person&lt;/code&gt; object can be deconstructed. It looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype person3
  N : string, A: number &amp;gt;&amp;gt; P;
  ___________________________
  [N A] : person &amp;gt;&amp;gt; P;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The way to read this type of rule is that, if &lt;code&gt;[N A]&lt;/code&gt; is a &lt;code&gt;person&lt;/code&gt; then &lt;code&gt;N&lt;/code&gt; is a &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;A&lt;/code&gt; is a number. With that loaded into Shen, &lt;code&gt;get-age&lt;/code&gt; type checks:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define get-age
   { person --&amp;gt; number }
   [N A] -&amp;gt; A)
get-age : (person --&amp;gt; number)

(0+) (get-age [&quot;Person&quot; 42])
42 : number
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The need to create a left rule, dual to the right rule, is common enough that Shen has a short method of defining both in one definition. It looks like this - note the use of &#39;=&#39; instead of &#39;_&#39; in the separator line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype person
   N : string; A : number;
   =======================
   [N A] : person;)

(define get-age
   { person --&amp;gt; number }
   [N A] -&amp;gt; A)
get-age : (person --&amp;gt; number)

(0+) (get-age [&quot;Person&quot; 42])
42 : number
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above &lt;code&gt;datatype&lt;/code&gt; is equivalent to declaring the two rules:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype person
  N : string; A : number;
  _______________________
  [N A] : person;

  N : string, A: number &amp;gt;&amp;gt; P;
  ___________________________
  [N A] : person &amp;gt;&amp;gt; P;)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Controlling type checking&lt;/h2&gt;

&lt;p&gt;When progamming at the REPL of Shen it&#39;s common to create &lt;code&gt;datatype&lt;/code&gt; definitions that are no longer needed, or part of a line of thought you don&#39;t want to pursue. Shen provides ways of excluding or including rules in the typechecker as needed. When defining a set of rules in a &lt;code&gt;datatype&lt;/code&gt;, that &lt;code&gt;datatype&lt;/code&gt; is given a name:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype this-is-the-name
   ...
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The rules within that definition can be removed from selection by the typechecker using &lt;code&gt;preclude&lt;/code&gt;, which takes a list of &lt;code&gt;datatype&lt;/code&gt; names to ignore during type checking:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(preclude [this-is-the-name])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To re-add a &lt;code&gt;dataype&lt;/code&gt;, use &lt;code&gt;include&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(include [this-is-the-name])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is also &lt;code&gt;include-all-but&lt;/code&gt; and &lt;code&gt;preclude-all-but&lt;/code&gt; to include or remove all but the listed names. These commands are useful for removing definitions you no longer want to use at the REPL, but also for speeding up type checking in a given file if you know the file only uses a particular set of datatypes.&lt;/p&gt;

&lt;h2&gt;Enumerations&lt;/h2&gt;

&lt;p&gt;An example of an enumeration type would be days of the week. In an ML style language this can be done like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;datatype days =   monday | tuesday | wednesday
                | thursday | friday | saturday | sunday
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In Shen this would be done using multiple sequent calculus rules.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype days
    ____________
    monday : day;

    ____________
    tuesday : day;

    ____________
    wednesday : day;

    ____________
    thursday : day;

    ____________
    friday : day;

    ____________
    saturday : day;

    ____________
    sunday : day;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here there are no rules above the dashed underscore line, meaning that the given symbol is of the type &lt;code&gt;day&lt;/code&gt;. A function that uses this type would look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define day-number
  { day --&amp;gt; number }
  monday    -&amp;gt; 0
  tuesday   -&amp;gt; 1
  wednesday -&amp;gt; 2
  thursday  -&amp;gt; 3
  friday    -&amp;gt; 4
  saturday  -&amp;gt; 5
  sunday    -&amp;gt; 6)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&#39;s quite verbose to define a number of enumeration types like this. It&#39;s possible to add a test above the dashed underline which allows being more concise. The test is introduced using &lt;code&gt;if&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype days
  if (element? Day [monday tuesday wednesday thursday friday saturday sunday])
  ____________________________________________________________________________
  Day : day;)

(0+) monday : day
monday : day
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Any Shen code can be used in these test conditions. Multiple tests can be combined:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype more-tests
  if (number? X)
  if (&amp;gt;= X 5)
  if (&amp;lt;= X 10)
  ___________
  X : between-5-and-10;)

  (2+) 5 : between-5-and-10
  5 : between-5-and-10

  (3+) 4 : between-5-and-10
  [error shen &quot;type error\n&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Polymorphic types&lt;/h2&gt;

&lt;p&gt;To create types that are polymorphic (ie. generic), like the built-in &lt;code&gt;list&lt;/code&gt; type, include a free variable representing the type. For example, something like the built in list where the list elements are stored as pairs can be approximated with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype my-list
   _____________________
   my-nil : (my-list A);

   X : A; Y : (my-list A);
   ========================
   (@p X Y) : (my-list A);)


(define my-cons
  { A --&amp;gt; (my-list A) --&amp;gt; (my-list A) }
  X Y -&amp;gt; (@p X Y))

(0+) (my-cons 1 my-nil)
(@p 1 my-nil) : (my-list number)

(1+) (my-cons 1 (my-cons 2 my-nil))
(@p 1 (@p 2 my-nil)) : (my-list number)

(2+) (my-cons &quot;a&quot; (my-cons &quot;b&quot; my-nil))
(@p &quot;a&quot; (@p &quot;b&quot; my-nil)) : (my-list string)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the use of the &#39;=====&#39; rule to combine left and right rules. This is required to enable writing something like &lt;code&gt;my-car&lt;/code&gt; which requires proving that the type of the &lt;code&gt;car&lt;/code&gt; of the list is of type &lt;code&gt;A&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define my-car
   { (my-list A) --&amp;gt; A }
   (@p X Y) -&amp;gt; X)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;List encoded with size&lt;/h2&gt;

&lt;p&gt;Using peano numbers we can create a list where the length of the list is part of the type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype list-n
  ______
  [] : (list-n zero A);

  X : A; Y : (list-n N A);
  ================================
  [ X | Y ] : (list-n (succ N) A);)      

(define my-tail
  { (list-n (succ N) A) --&amp;gt; (list-n N A) }
  [Hd | Tl] -&amp;gt; Tl)

(define my-head
  { (list-n (succ N) A) --&amp;gt; A }
  [Hd | Tl] -&amp;gt; Hd)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This gives a typesafe &lt;code&gt;head&lt;/code&gt; and &lt;code&gt;tail&lt;/code&gt; operation whereby they can&#39;t be called on an empty list:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(0+) [] : (list-n zero number)
[] : (list-n zero number)

(1+) [1] : (list-n (succ zero) number)
[1] : (list-n (succ zero) number)

(2+) (my-head [])
[error shen &quot;type error\n&quot;]

(3+) (my-head [1])
1 : number

(4+) (my-tail [1 2 3])
[2 3] : (list-n (succ (succ zero)) number)

(5+) (my-tail [])
[error shen &quot;type error\n&quot;]      
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Power and Responsibility&lt;/h2&gt;

&lt;p&gt;Shen gives a lot of power in creating types, but trusts you to make those types consistent. For example, the following creates an inconsistent type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(datatype person
  N : string; A : number;
  _______________________
  [N A] : person;

  N : string; A : string;
  _______________________
  [N A] : person;

  N : string, A: number &amp;gt;&amp;gt; P;
  ___________________________
  [N A] : person &amp;gt;&amp;gt; P;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we are telling Shen that a &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;number&lt;/code&gt; in a &lt;code&gt;list&lt;/code&gt; is a &lt;code&gt;person&lt;/code&gt;, and so too is a &lt;code&gt;string&lt;/code&gt; and another &lt;code&gt;string&lt;/code&gt;. But the third rule states that given a &lt;code&gt;person&lt;/code&gt;, that is is composed of a &lt;code&gt;string&lt;/code&gt; and a &lt;code&gt;number&lt;/code&gt; only. This leads to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(0+) (get-age [&quot;Person&quot; &quot;Person&quot;])
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will hang for a long time as Shen attempts to resolve the error we&#39;ve created.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Shen provides a programmable type system, but the responsibility lies on the programmer for making sure the types are consisitent. The examples given here provide a brief overview. For much more see &lt;a href=&quot;https://www.amazon.co.uk/Book-Shen-Third-Mark-Tarver/dp/1784562130&quot;&gt;The Book of Shen&lt;/a&gt;. The &lt;a href=&quot;http://shenlanguage.org/osmanual.htm&quot;&gt;Shen OS Kernel Manual&lt;/a&gt; also gives some examples. There are posts on the &lt;a href=&quot;https://groups.google.com/forum/?hl=en#!forum/qilang&quot;&gt;Shen Mailing List&lt;/a&gt; that have more advanced examples of Shen types. Mark Tarver has a &lt;a href=&quot;http://shenlanguage.org/shenpaper.pdf&quot;&gt;case study&lt;/a&gt; showing converting a lisp interpreter in Shen to use types.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Getting Started with Mercury</title>
   <link href="http://bluishcoder.co.nz/2019/06/23/getting-started-with-mercury.html"/>
   <updated>2019-06-23T23:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2019/06/23/getting-started-with-mercury</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;https://www.mercurylang.org/&quot;&gt;Mercury&lt;/a&gt; is a logic programming
language, similar to Prolog, but with static types. It feels like a
combination of SML and Prolog at times. It was designed to help with
programming large systems - that is large programs, large teams and
better reliability, etc. The commercial product &lt;a href=&quot;https://www.princexml.com/&quot;&gt;Prince
XML&lt;/a&gt; is written in Mercury.&lt;/p&gt;

&lt;p&gt;I&#39;ve played around with Mercury in the past but haven&#39;t done anything
substantial with it. Recently I picked it up again. This post is a
short introduction to building Mercury, and some example &quot;Hello World&quot;
style programs to test the install.&lt;/p&gt;

&lt;h2&gt;Build&lt;/h2&gt;

&lt;p&gt;Mercury is written in the Mercury language itself. This means it needs
a Mercury compiler to bootstrap from. The way I got a build going from
source was to download the source for a &lt;a href=&quot;http://dl.mercurylang.org/index.html&quot;&gt;release of the
day&lt;/a&gt; version, build that, then
use that build to build the Mercury source from github. The steps are
outlined in the &lt;a href=&quot;https://github.com/Mercury-Language/mercury/blob/master/README.bootstrap&quot;&gt;README.bootstrap&lt;/a&gt;
file, but the following commands are the basic steps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ wget http://dl.mercurylang.org/rotd/mercury-srcdist-rotd-2019-06-22.tar.gz
$ tar xvf mercury-srcdist-rotd-2019-06-22.tar.gz
$ cd mercury-srcdist-rotd-2019-06-22
$ ./configure --enable-minimal-install --prefix=/tmp/mercury
$ make
$ make install
$ cd ..
$ export PATH=/tmp/mercury/bin:$PATH
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this minimal compiler the main source can be built. Mercury has a
number of backends, called &#39;grades&#39; in the documentation. Each of
these grades makes a number of tradeoffs in terms of generated
code. They define the platform (C, assembler, Java, etc), whether GC
is used, what type of threading model is available (if any), etc. The
&lt;a href=&quot;https://adventuresinmercury.blogspot.com/&quot;&gt;Adventures in Mercury&lt;/a&gt;
blog has an &lt;a href=&quot;https://adventuresinmercury.blogspot.com/2011/11/making-grade.html&quot;&gt;article on some of the different
grades&lt;/a&gt;. Building
all of them can take a long time - multiple hours - so it pays to
limit it if you don&#39;t need some of the backends.&lt;/p&gt;

&lt;p&gt;For my purposes I didn&#39;t need the CSharp backend, but wanted to
explore the others. I was ok with the time tradeoff of building the
system. To build from the &lt;code&gt;master&lt;/code&gt; branch of the github repository I
did the following steps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/Mercury-Language/mercury
$ cd mercury
$ ./prepare.sh
$ ./configure --enable-nogc-grades --disable-csharp-grade \
              --prefix=/home/myuser/mercury
$ make PARALLEL=-j4
$ make install PARALLEL=-j4
$ export PATH=/home/myuser/mercury/bin:$PATH
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Change the &lt;code&gt;prefix&lt;/code&gt; to where you want Mercury installed. Add the
relevant directories to the PATH as specified by the end of the build
process.&lt;/p&gt;

&lt;h2&gt;Hello World&lt;/h2&gt;

&lt;p&gt;A basic &quot;Hello World&quot; program in Mercury looks like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- module hello.

:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.

:- implementation.
main(IO0, IO1) :-
    io.write_string(&quot;Hello World!\n&quot;, IO0, IO1).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this code in a &lt;code&gt;hello.m&lt;/code&gt; file, it can be built and run with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ mmc --make hello
Making Mercury/int3s/hello.int3
Making Mercury/ints/hello.int
Making Mercury/cs/hello.c
Making Mercury/os/hello.o
Making hello    
$ ./hello
Hello World!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first line defines the name of the module:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- module hello.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Following that is the definitions of the public interface of the module:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We publically import the &lt;code&gt;io&lt;/code&gt; module, as we use &lt;code&gt;io&lt;/code&gt; definitions in
the &lt;code&gt;main&lt;/code&gt; predicate. This is followed by a declaration of the
interface of &lt;code&gt;main&lt;/code&gt; - like C this is the user function called by the
runtime to execute the program. The definition here declares that
&lt;code&gt;main&lt;/code&gt; is a predicate, it takes two arguments, of type &lt;code&gt;io&lt;/code&gt;. This is a
special type that represents the &quot;state of the world&quot; and is how I/O
is handled in Mercury. The first argument is the &quot;input world state&quot;
and the second argument is the &quot;output world state&quot;. All I/O functions
take these two arguments - the state of the world before the function
and the state of the world after.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;mode&lt;/code&gt; line declares aspects of a predicate related to the logic
programming side of things. In this case we declare that the two
arguments passed to &lt;code&gt;main&lt;/code&gt; have the &quot;destructive input&quot; mode and the
&quot;unique output&quot; mode respectively. These modes operate similar to how
linear types work in other languages, and the &lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_ref/Unique-modes.html#Unique-modes&quot;&gt;reference manual has a
section describing
them&lt;/a&gt;. For
now the details can be ignored. The &lt;code&gt;is det&lt;/code&gt; portion identifies the
function as being deterministic. It always succeeds, doesn&#39;t backtrack
and only has one result.&lt;/p&gt;

&lt;p&gt;The remaining code is the implementation. In this case it&#39;s just the implementation of the &lt;code&gt;main&lt;/code&gt; function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main(IO0, IO1) :-
    io.write_string(&quot;Hello World!\n&quot;, IO0, IO1).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The two arguments to &lt;code&gt;main&lt;/code&gt;, are the &lt;code&gt;io&lt;/code&gt; types representing the before and after representation of the world. We call &lt;code&gt;write_string&lt;/code&gt; to display a string, passing it the input world state, &lt;code&gt;IO0&lt;/code&gt; and receiving the new world state in &lt;code&gt;IO1&lt;/code&gt;. If we wanted to call an additional output function we&#39;d need to thread these variables, passing the obtained output state as the input to the new function, and receiving a new output state. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main(IO0, IO1) :-
    io.write_string(&quot;Hello World!\n&quot;, IO0, IO1),
    io.write_string(&quot;Hello Again!\n&quot;, IO1, IO2).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This state threading can be tedious, especially when refactoring - the need to renumber or rename variables is a pain point. Mercury has syntactic sugar for this called &lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_ref/State-variables.html#State-variables&quot;&gt;state variables&lt;/a&gt;, enabling this function to be written like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main(!IO) :-
    io.write_string(&quot;Hello World!\n&quot;, !IO),
    io.write_string(&quot;Hello Again!\n&quot;, !IO).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the compiler sees &lt;code&gt;!Variable_name&lt;/code&gt; in an argument list it creates two arguments with automatically generated names as needed.&lt;/p&gt;

&lt;p&gt;Another syntactic short cut can be done in the &lt;code&gt;pred&lt;/code&gt; and &lt;code&gt;mode&lt;/code&gt; lines. They can be combined into one line that looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- pred main(io::di, io::uo) is det.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the modes &lt;code&gt;di&lt;/code&gt; and &lt;code&gt;uo&lt;/code&gt; are appended to the type prefixed with a &lt;code&gt;::&lt;/code&gt;. The resulting program looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- module hello.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
main(!IO) :-
    io.write_string(&quot;Hello World!\n&quot;, !IO),
    io.write_string(&quot;Hello Again!\n&quot;, !IO).
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Factorial&lt;/h2&gt;

&lt;p&gt;The following is an implementation of factorial:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- module fact.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int.
:- pred fact(int::in, int::out) is det.

fact(N, X) :-
  ( N = 1 -&amp;gt; X = 1 ; fact(N - 1, X0), X = N * X0 ).

main(!IO) :-
  fact(5, X),
  io.print(&quot;fact(5, &quot;, !IO),
  io.print(X, !IO),
  io.print(&quot;)\n&quot;, !IO).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the implementation section here we import the &lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_library/int.html#int&quot;&gt;int
module&lt;/a&gt;
to access functions across machine integers. The &lt;code&gt;fact&lt;/code&gt; predicate is
declared to take two arguments, both of type &lt;code&gt;int&lt;/code&gt;, the first an input
argument and the second an output argument.&lt;/p&gt;

&lt;p&gt;The definition of &lt;code&gt;fact&lt;/code&gt; uses Prolog syntax for an if/then
statement. It states that if &lt;code&gt;N&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt; then (the &lt;code&gt;-&amp;gt;&lt;/code&gt; token) the
output variable, &lt;code&gt;X&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt;. Otherwise (the &lt;code&gt;;&lt;/code&gt; token), calculate the
factorial recursively using an intermediate variable &lt;code&gt;X0&lt;/code&gt; to hold the
temporary result.&lt;/p&gt;

&lt;p&gt;There&#39;s a few other ways this could be written. Instead of the Prolog style if/then, we can use an if/then syntax that Mercury has:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fact(N, X) :-
  ( if N = 1 then X = 1 else fact(N - 1, X0), X = N * X0 ).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Instead of using predicates we can declare &lt;code&gt;fact&lt;/code&gt; to be a function. A function has no output variables, instead it returns a result just like functions in standard functional programming languages. The changes for this are to declare it as a function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- func fact(int) = int.
fact(N) = X :-
  ( if N = 1 then X = 1 else X = N * fact(N - 1) ).

main(!IO) :-
  io.print(&quot;fact(5, &quot;, !IO),
  io.print(fact(5), !IO),
  io.print(&quot;)\n&quot;, !IO)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice now that the call to &lt;code&gt;fact&lt;/code&gt; looks like a standard function call and is inlined into the &lt;code&gt;print&lt;/code&gt; call in &lt;code&gt;main&lt;/code&gt;. A final syntactic shortening of function implementations enables removing the &lt;code&gt;X&lt;/code&gt; return variable name and returning directly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fact(N) = (if N = 1 then 1 else N * fact(N - 1)).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because this implementation uses machine integers it won&#39;t work for values that can overflow. Mercury comes with an arbitrary precision integer module, &lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_library/integer.html#integer&quot;&gt;integer&lt;/a&gt;, that allows larger factorials. Replacing the use of the &lt;code&gt;int&lt;/code&gt; module with &lt;code&gt;integer&lt;/code&gt; and converting the static integer numbers is all that is needed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:- module fact.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module integer.
:- func fact(integer) = integer.

fact(N) = (if N = one then one else N * fact(N - one)).

main(!IO) :-
  io.print(&quot;fact(1000, &quot;, !IO),
  io.print(fact(integer(1000)), !IO),
  io.print(&quot;)\n&quot;, !IO).
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;There&#39;s a lot more to Mercury. These are just first steps to test the
system works. I&#39;ll write more about it in later posts. Some further
reading:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://adventuresinmercury.blogspot.com&quot;&gt;Adventures in Mercury&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_library/index.html&quot;&gt;Library reference manual&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_user_guide/index.html&quot;&gt;Users guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.mercurylang.org/information/doc-latest/mercury_ref/index.html&quot;&gt;Language Reference Manual&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.mercurylang.org/documentation/papers/book.pdf&quot;&gt;Ralph Becket Mercury Tutorial (PDF)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/Mercury-Language/mercury/wiki&quot;&gt;Mercury Wiki&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</content>
 </entry>
 
 <entry>
   <title>Generalized Algebraic Data Types in ATS</title>
   <link href="http://bluishcoder.co.nz/2018/10/16/generalized-algebraic-data-types-in-ats.html"/>
   <updated>2018-10-16T18:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2018/10/16/generalized-algebraic-data-types-in-ats</id>
   <content type="html">&lt;p&gt;The &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS programming language&lt;/a&gt; supports
defining Generalized Algebraic Data Types (GADTS). They allow defining
datatypes where the constructors for the datatype are explicitly
defined by the programmer. This has a number of uses and I&#39;ll go
through some examples in this post. GADTs are sometimes referred to as
Guarded Recursive Datatypes.&lt;/p&gt;

&lt;p&gt;Some useful resources for reading up on GADTs that I used to write
this post are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Generalized_algebraic_data_type&quot;&gt;Wikipedia page on GADT&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://en.wikibooks.org/wiki/Haskell/GADT&quot;&gt;Haskell/GADT Wikibook&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://wiki.haskell.org/GADTs_for_dummies&quot;&gt;GADTs for Dummies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.ats-lang.org/MYDATA/GRDT-popl03.pdf&quot;&gt;Guarded Recursive Datatype Constructors&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The examples here were tested with ATS2-0.3.11.&lt;/p&gt;

&lt;h2&gt;Arithmetic Expressions&lt;/h2&gt;

&lt;p&gt;This is probably the most common demonstration of GADT usage and it&#39;s
useful to see how to do it in ATS. The example is taken from the
&lt;a href=&quot;https://en.wikibooks.org/wiki/Haskell/GADT&quot;&gt;Haskell/GADT Wikibook&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;First we&#39;ll create datatype to represent a simple expression language,
and write an evaluation function for it, without using GADTs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

datatype Expr  =
  | I of int
  | Add of (Expr, Expr)
  | Mul of (Expr, Expr)

fun eval (x:Expr): int =
  case+ x of
  | I i =&amp;gt; i
  | Add (t1, t2) =&amp;gt; eval(t1) + eval(t2)
  | Mul (t1, t2) =&amp;gt; eval(t1) * eval(t2)


implement main0() = let
  val term = Mul(I(2), I(4))
  val res = eval(term)
in
  println!(&quot;res=&quot;, res)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;Expr&lt;/code&gt; is a datatype with three constructors. &lt;code&gt;I&lt;/code&gt; represents an
integer, &lt;code&gt;Add&lt;/code&gt; adds two expressions together and &lt;code&gt;Mul&lt;/code&gt; multiples two
expressions. The &lt;code&gt;eval&lt;/code&gt; function pattern matches on these and
evaluates them. The example can be compiled with the following if
placed in a file &lt;code&gt;arith1.dats&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -DATS_MEMALLOC_LIBC -o arith1 arith1.dats
$ ./arith1
res=8
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we extend the expression language with another type, booleans, and
add an &lt;code&gt;Expr&lt;/code&gt; constructor to compare for equality:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;datatype Expr  =
  | I of int
  | B of bool
  | Add of (Expr, Expr)
  | Mul of (Expr, Expr)
  | Eq of (Expr, Expr)

(* Does not typecheck *)
fun eval (x:Expr): int =
  case+ x of
  | I i =&amp;gt; i
  | B b =&amp;gt; b
  | Add (t1, t2) =&amp;gt; eval(t1) + eval(t2)
  | Mul (t1, t2) =&amp;gt; eval(t1) * eval(t2)
  | Eq (t1, t2) =&amp;gt; eval(t1) = eval(t2)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code fails to typecheck - the &lt;code&gt;eval&lt;/code&gt; function is defined to
return an &lt;code&gt;int&lt;/code&gt; but the &lt;code&gt;B b&lt;/code&gt; pattern match returns a boolean. We can
work around this by making the result value of &lt;code&gt;eval&lt;/code&gt; return a
datatype that can represent either an &lt;code&gt;int&lt;/code&gt; or a &lt;code&gt;bool&lt;/code&gt; but then we
have to add code throughout &lt;code&gt;eval&lt;/code&gt; to detect the invalid addition or
multiplication of a boolean and raise a runtime error. Ideally we&#39;d
like to have make it impossible to construct invalid expressions such
that they error out at compile time.&lt;/p&gt;

&lt;p&gt;We can imagine the type constructors for &lt;code&gt;Expr&lt;/code&gt; as if they were
functions with a type signature. The type signature of the
constructors would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun I(n:int): Expr
fun B(b:bool): Expr
fun Add(t1:Expr, t2:Expr): Expr
fun Mul(t1:Expr, t1:Expr): Expr
fun Eq(t1:Expr, t2:Expr): Expr
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The problem here is that &lt;code&gt;Add&lt;/code&gt; and &lt;code&gt;Mul&lt;/code&gt; both take &lt;code&gt;Expr&lt;/code&gt; as arguments
but we want to restrict them to integer expressions only - we need to
differentiate between integer and boolean expressions. We&#39;d like to
add a type index to the &lt;code&gt;Expr&lt;/code&gt; datatype that indicates if it is a
boolean or an integer expression and change the constructors so they
have types like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun I(n:int): Expr int
fun B(b:bool): Expr bool
fun Add(t1:Expr int, t2:Expr int): Expr int
fun Mul(t1:Expr int, t1:Expr int): Expr int
fun Eq(t1:Expr int, t2:Expr int): Expr bool
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using these constructors would make it impossible to create an
expression that would give a runtime error in an &lt;code&gt;eval&lt;/code&gt;
function. Creating an &lt;code&gt;Expr&lt;/code&gt; with a type index looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;datatype Expr(a:t@ype)  =
  | I(a) of int
  | B(a) of bool
  | Add(a) of (Expr int, Expr int)
  | Mul(a) of (Expr int, Expr int)
  | Eq(a) of (Expr int, Expr int)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This adds a type index of sort &lt;code&gt;t@ype&lt;/code&gt;. A &#39;sort&#39; in ATS is the type of
type indexes. The &lt;code&gt;t@ype&lt;/code&gt; is for types that have a flat memory
structure of an unknown size. The &#39;@&#39; sigil looks odd inside the name,
but &#39;@&#39; is used elsewhere in ATS when defining flat records and tuples
which is a useful mnemonic for remembering what the &#39;@&#39; within the
sort name means.&lt;/p&gt;

&lt;p&gt;This doesn&#39;t help our case though as the type signatures for the
constructors would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun I(n:int): Expr a
fun B(b:bool): Expr a
fun Add(t1:Expr int, t2:Expr int): Expr a
fun Mul(t1:Expr int, t1:Expr int): Expr a
fun Eq(t1:Expr int, t2:Expr int): Expr a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is still the problem that an &lt;code&gt;Expr a&lt;/code&gt; is not an &lt;code&gt;Expr int&lt;/code&gt; for
&lt;code&gt;Add&lt;/code&gt;, &lt;code&gt;Mul&lt;/code&gt; and &lt;code&gt;Eq&lt;/code&gt;, and requiring runtime errors when pattern
matching. This is where GADTs come in. GADTs enable defining a
datatype that provides constructors where the generic &lt;code&gt;a&lt;/code&gt; of the type
index can be constrained to a specific type, different for each
constructor. The &lt;code&gt;Expr&lt;/code&gt; datatype becomes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;datatype Expr(t@ype)  =
  | I(int) of int
  | B(bool) of bool
  | Add(int) of (Expr int, Expr int)
  | Mul(int) of (Expr int, Expr int)
  | Eq(bool) of (Expr int, Expr int)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The constructor type signature now match those that we wanted earlier
and it becomes possible to check at compile time for invalid
expressions. The &lt;code&gt;eval&lt;/code&gt; functions looks similar, but is parameterized
over the type index:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun{a:t@ype} eval(x:Expr a): a =
  case+ x of
  | I i =&amp;gt; i
  | B b =&amp;gt; b
  | Add (t1, t2) =&amp;gt; eval(t1) + eval(t2)
  | Mul (t1, t2) =&amp;gt; eval(t1) * eval(t2)
  | Eq (t1, t2) =&amp;gt; eval(t1) = eval(t2)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &quot;&lt;code&gt;{a:t@ype}&lt;/code&gt;&quot; syntax following &lt;code&gt;fun&lt;/code&gt; is ATS&#39; way of defining a
function template where &lt;code&gt;a&lt;/code&gt; is the template argument. ATS will
generate a new function specific for each &lt;code&gt;a&lt;/code&gt; type used in the
program.&lt;/p&gt;

&lt;p&gt;An example &lt;code&gt;main&lt;/code&gt; function to demonstrate the new GADT enabled &lt;code&gt;Expr&lt;/code&gt;
and &lt;code&gt;eval&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0() = let
  val term1 = Eq(I(5), Add(I(1), I(4)))
  val term2 = Mul(I(2), I(4))
  val res1 = eval(term1)
  val res2 = eval(term2)
in
  println!(&quot;res1=&quot;, res1, &quot; and res2=&quot;, res2)
end

$ patscc -DATS_MEMALLOC_LIBC -o arith2 arith2.dats
$ ./arith2
res1=true and res2=8
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may have noticed that our &lt;code&gt;Expr&lt;/code&gt; type can&#39;t represent equality
between booleans, or between booleans and integers. It&#39;s defined to
only allow equality between integers. It&#39;s possible to make equality
polymorphic but I&#39;ll go through this later as it brings up some more
complicated edge cases in types with ATS beyond just using GADTs.&lt;/p&gt;

&lt;h2&gt;Typesafe sprintf&lt;/h2&gt;

&lt;p&gt;This example of GADT usage in ATS tries to implement a &lt;code&gt;sprintf&lt;/code&gt;
function that allows providing a format specification to &lt;code&gt;sprintf&lt;/code&gt;
which then processes it and accepts arguments of types as defined by
the format specification.&lt;/p&gt;

&lt;p&gt;The format specification is defined as a GADT:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;datatype Format (a:type) =
  | I(int -&amp;lt;cloref1&amp;gt; a) of (Format a)
  | S_(a) of (string, Format a)
  | S0(string) of string
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each constructor represents part of a format string. The type index is the type that &lt;code&gt;sprintf&lt;/code&gt; will return given a format string for that type. &lt;code&gt;sprintf&lt;/code&gt; is declared as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun sprintf {a:type} (fmt: Format a): a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here are some example invocations and the types that should result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Returns a string
sprintf (S0 &quot;hello&quot;)

// Returns a string
sprintf (S_ (&quot;hello&quot;, S0 &quot;world&quot;))

// Returns a function that takes an int and returns a string
sprintf (I (S0 &quot;&amp;lt;- is a number&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The last example shows how &lt;code&gt;sprintf&lt;/code&gt; emulates variable arguments using closures. By returning a function any immediately following tokens are treated as arguments to that function. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sprintf (I (S0 &quot;&amp;lt;- is a number&quot;)) 42
(int -&amp;gt; string) 42
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With some syntactic sugar using currying we can make this look
nicer. &lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/x892.html&quot;&gt;Curried functions&lt;/a&gt;
is a feature that isn&#39;t often used in ATS as it requires the garbage
collector (to clean up partially curried functions) and performance is
diminished due to the allocation of closures but it&#39;s useful for this example.&lt;/p&gt;

&lt;p&gt;With the &lt;code&gt;Format&lt;/code&gt; datatype defined, here&#39;s the implementation of &lt;code&gt;sprintf&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun sprintf {a:type} (fmt: Format a): a = let
  fun aux {a:type}(pre: string, fmt&#39;: Format a): a =
    case fmt&#39; of
    | I fmt =&amp;gt; (lam (i) =&amp;gt; aux(append(pre, int2string(i)), fmt))
    | S_ (s, fmt) =&amp;gt; aux(append(pre, s), fmt)
    | S0 s =&amp;gt; append(pre, s)
in
  aux(&quot;&quot;, fmt)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It uses an inner function, &lt;code&gt;aux&lt;/code&gt;, that does the work of deconstructing the format argument and returning a closure when needed, and appending strings as the result string is computed. For this example I&#39;m cheating with memory management to keep the focus on GADT, and off dealing with the intricacies of linear strings. The example should be run with the garbage collector to free the allocated strings.&lt;/p&gt;

&lt;p&gt;Here&#39;s an example of executing what we have so far:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0() = let
  val fmt = S_ (&quot;X: &quot;, (I (S_ (&quot; Y: &quot;, (I (S0 &quot;&quot;))))))
  val s = sprintf fmt 5 10
in
  println!(s)
end

$ ./format
X: 5 Y: 10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The format string is pretty ugly though. Some helper functions make it a bit more friendly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun Str {a:type} (s: string) (fmt: Format a) = S_ (s, fmt)
fun Int {a:type} (fmt: Format a) = I (fmt)
fun End (s:string) = S0 (s)

infixr 0 &amp;gt;:
macdef &amp;gt;: (f, x) = ,(f) ,(x)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the format definition is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val fmt = Str &quot;X: &quot; &amp;gt;: Int &amp;gt;: Str &quot; Y: &quot; &amp;gt;: Int &amp;gt;: End &quot;&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The string handling functions that I threw together to append strings and convert an integer to a string without dealing with linear strings follow.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun append(s0: string, s1: string): string = let
  extern castfn from(s:string):&amp;lt;&amp;gt; Strptr1
  extern castfn to(s:Strptr0):&amp;lt;&amp;gt; string
  extern prfun drop(s:Strptr1):&amp;lt;&amp;gt; void
  val s0&#39; = from(s0)
  val s1&#39; = from(s1)
  val r = strptr_append(s0&#39;, s1&#39;)
  prval () = drop(s0&#39;)
  prval () = drop(s1&#39;)
in
  to(r)
end

fun int2string(x: int): string =
  tostring(g0int2string x) where {
    extern castfn tostring(Strptr0):&amp;lt;&amp;gt; string
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Issues&lt;/h2&gt;

&lt;p&gt;These example of GADT usage were pulled from the papers and articles mentioned at the beginning of the post. They were written for Haskell or Dependent ML (a predecessor to ATS). There may be better ways of approaching the problem in ATS and some constraints on the way ATS generates C code limits how GADTs can be used. One example of the limitation was mentioned in the first example of the expression evaluator.&lt;/p&gt;

&lt;p&gt;If the &lt;code&gt;Expr&lt;/code&gt; datatype is changed so that &lt;code&gt;Eq&lt;/code&gt; can work on any type, not just &lt;code&gt;int&lt;/code&gt;, then a compile error results:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;datatype Expr(a:t@ype)  =
  | I(a) of int
  | B(a) of bool
  | Add(a) of (Expr int, Expr int)
  | Mul(a) of (Expr int, Expr int)
  | Eq(a) of (Expr a, Expr a)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error occurs due to the &lt;code&gt;Eq&lt;/code&gt; branch in the case statement in &lt;code&gt;eval&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun{a:t@ype} eval(x:Expr a): a =
  case+ x of
  | I i =&amp;gt; i
  | B b =&amp;gt; b
  | Add (t1, t2) =&amp;gt; eval(t1) + eval(t2)
  | Mul (t1, t2) =&amp;gt; eval(t1) * eval(t2)
  | Eq (t1, t2) =&amp;gt; eval(t1) = eval(t2)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The compiler is unable to find a match for the overloaded &lt;code&gt;=&lt;/code&gt; call for the general case of any &lt;code&gt;a&lt;/code&gt; (vs the specific case of &lt;code&gt;int&lt;/code&gt; as it was before). This is something &lt;a href=&quot;https://bluishcoder.co.nz/2011/10/19/overloading-functions-in-ats.html&quot;&gt;I&#39;ve written about before&lt;/a&gt; and the workaround in that post gets us past that error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;extern fun{a:t@ype} equals(t1:a, t2:a): bool
implement equals&amp;lt;int&amp;gt;(t1,t2) = g0int_eq(t1,t2)
implement equals&amp;lt;bool&amp;gt;(t1,t2) = eq_bool0_bool0(t1,t2)

fun{a:t@ype} eval(x:Expr a): a =
  case+ x of
  | I i =&amp;gt; i
  | B b =&amp;gt; b
  | Add (t1, t2) =&amp;gt; eval(t1) + eval(t2)
  | Mul (t1, t2) =&amp;gt; eval(t1) * eval(t2)
  | Eq (t1, t2) =&amp;gt; equals(eval(t1), eval (t2))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the program typechecks but fails to compile the generated C code. This can usually be resolved by explicitly stating the template parameters in template function calls:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun{a:t@ype} eval(x:Expr a): a =
  case+ x of
  | I i =&amp;gt; i
  | B b =&amp;gt; b
  | Add (t1, t2) =&amp;gt; eval&amp;lt;int&amp;gt;(t1) + eval&amp;lt;int&amp;gt;(t2)
  | Mul (t1, t2) =&amp;gt; eval&amp;lt;int&amp;gt;(t1) * eval&amp;lt;int&amp;gt;(t2)
  | Eq (t1, t2) =&amp;gt; equals&amp;lt;?&amp;gt;(eval&amp;lt;?&amp;gt;(t1), eval&amp;lt;?&amp;gt;(t2))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The problem here is what types to put in the &#39;&lt;code&gt;?&lt;/code&gt;&#39; in this snippet? The &lt;code&gt;Expr&lt;/code&gt; type defines this as being any &lt;code&gt;a&lt;/code&gt; but we want to constrain it to the index used by &lt;code&gt;t1&lt;/code&gt; and &lt;code&gt;t2&lt;/code&gt; but I don&#39;t think ATS allows us to declare that. &lt;a href=&quot;https://groups.google.com/forum/#!topic/ats-lang-users/fIjL6bpAGno&quot;&gt;This mailing list thread&lt;/a&gt; discusses the issue with some workarounds.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Concurrent and Distributed Programming in Web Prolog</title>
   <link href="http://bluishcoder.co.nz/2018/09/24/concurrent-and-distributed-programming-in-web-prolog.html"/>
   <updated>2018-09-24T18:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2018/09/24/concurrent-and-distributed-programming-in-web-prolog</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://www.swi-prolog.org/&quot;&gt;SWI Prolog&lt;/a&gt; is an open source Prolog implementation with good documentation and many interesting libraries. One library that was published recently is &lt;a href=&quot;https://github.com/Web-Prolog/swi-web-prolog/&quot;&gt;Web Prolog&lt;/a&gt;. While branded as a &#39;Web Logic Programming Language&#39; the implementation in the github repository runs under SWI Prolog and adds &lt;a href=&quot;https://www.erlang.org/&quot;&gt;Erlang&lt;/a&gt; style distributed concurrency. There is a &lt;a href=&quot;https://github.com/Web-Prolog/swi-web-prolog/raw/master/book/web-prolog.pdf&quot;&gt;PDF Book&lt;/a&gt; in the repository that goes into detail about the system. In this post I explore some of features.&lt;/p&gt;

&lt;h2&gt;Install SWI Prolog&lt;/h2&gt;

&lt;p&gt;The first step is to install and run the SWI Prolog development version. There is &lt;a href=&quot;http://www.swi-prolog.org/build/&quot;&gt;documentation on this&lt;/a&gt; but the following are the basic steps to download and build from the SWI Prolog github repository:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/SWI-Prolog/swipl-devel
$ cd swipl-devel
$ ./prepare
... answer yes to the various prompts ...
$ cp build.tmpl build
$ vim build
...change PREFIX to where you want to install...
$ make install
$ export PATH=&amp;lt;install location&amp;gt;/bin:$PATH
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There may be errors about building optional libraries. They can be ignored or &lt;a href=&quot;http://www.swi-prolog.org/build/Debian.html&quot;&gt;view dependancies&lt;/a&gt; to see how to install.&lt;/p&gt;

&lt;p&gt;The newly installed SWI Prolog build can be run with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ swipl
Welcome to SWI-Prolog (threaded, 64 bits, version 7.7.19-47-g4c3d70a09)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit http://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I recommend reading &lt;a href=&quot;https://www.metalevel.at/prolog/concepts&quot;&gt;Basic Concepts&lt;/a&gt; in &lt;a href=&quot;https://www.metalevel.at/prolog&quot;&gt;The Power of Prolog&lt;/a&gt; to get a grasp of Prolog syntax if you&#39;re not familiar with it.&lt;/p&gt;

&lt;h2&gt;Starting a Web Prolog node&lt;/h2&gt;

&lt;p&gt;Installing the Web Prolog libraries involves cloning the github repository and loading the prolog libraries held within. The system includes a web based tutorial and IDE where each connected web page is a web prolog node that can send and receive messages to other web prolog nodes. I&#39;ll beiefly mention this later but won&#39;t cover it in detail in this post - for now some simple examples will just use the SWI Prolog REPL. We&#39;ll need two nodes running, which can be done by running on different machines. On each machine run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/Web-Prolog/swi-web-prolog/
$ cd swi-web-prolog
$ swipl
...
?- [web_prolog].
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;[web_prolog].&lt;/code&gt; command at the prolog prompt loads the web prolog libraries. Once loaded we need to instantiate a node, which starts the socket server and machinery that handles messaging:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- node.
% Started server at http://localhost:3060/
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This starts a node on the default port &lt;code&gt;3060&lt;/code&gt;. If you&#39;re running multiple nodes on the same machine you can change the port by passing an argument to &lt;code&gt;node&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- node(localhost:3061).
% Started server at http://localhost:3061/
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the rest of this post I refer to node &lt;code&gt;A&lt;/code&gt; and node &lt;code&gt;B&lt;/code&gt; for the two nodes started above.&lt;/p&gt;

&lt;h2&gt;Basic example&lt;/h2&gt;

&lt;p&gt;Each process has an id that can be used to reference it. It is obtained via &lt;code&gt;self&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- self(Self).
Self = thread(1)@&#39;http://localhost:3061&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can send a message using &#39;&lt;code&gt;!&lt;/code&gt;&#39;. Like Erlang, it takes a process to send to and the data to send:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- self(Self),
   Self ! &#39;Hello World&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This posts &#39;Hello World&#39; to the current process mailbox. Messages can be received using &lt;code&gt;receive&lt;/code&gt;. This takes a series of patterns to match against and code to run if an item in the process mailbox matches that pattern. Like Erlang it is a selective receive - it will look through messages in the mailbox that match the pattern, not just the topmost message:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- receive({ M -&amp;gt; writeln(M) }).
Hello World
M = &#39;Hello World&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the &lt;code&gt;receive&lt;/code&gt; rules are enclosed in &#39;&lt;code&gt;{ ... }&lt;/code&gt;&#39; and are comprised of a pattern to match against and the code to run separated by &lt;code&gt;-&amp;gt;&lt;/code&gt;. Variables in the pattern are assigned the value of what they match. In this case &lt;code&gt;M&lt;/code&gt; is set to &lt;code&gt;Hello World&lt;/code&gt; as that&#39;s the message we sent earlier. More complex patterns are possible:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- $Self ! foo(1, 2, bar(&#39;hi&#39;, [ &#39;a&#39;, &#39;b&#39;, &#39;c&#39; ])).
Self = thread(1)@&#39;http://localhost:3061&#39;.

?- receive({ foo(A, B, bar(C, [D | E])) -&amp;gt; true }).
A = 1,
B = 2,
C = hi,
D = a,
E = [b, c].
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here I make use of a feature of the SWI Prolog REPL - prefixing a variable with &lt;code&gt;$&lt;/code&gt; will use the value that was assigned to that variable in a previous REPL command. This also shows matching on the head and tail of a list with the &lt;code&gt;[Head | Tail]&lt;/code&gt; syntax.&lt;/p&gt;

&lt;p&gt;To send to another process we just need to use the process identifier. In this case I can send a message from node A to node B:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# In Node A
?- self(Self).
Self = thread(1)@&#39;http://localhost:3060&#39;.

# This call blocks
?- receive({ M -&amp;gt; format(&#39;I got: ~s~n&#39;, [M])}).

# In Node B
?- thread(1)@&#39;http://localhost:3060&#39; ! &#39;Hi World&#39;.
true.

# Node A unblocks
I got: Hi World
M = &#39;Hi World&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Spawning processes&lt;/h2&gt;

&lt;p&gt;Use &lt;code&gt;spawn&lt;/code&gt; to spawn a new process the runs concurrencly on a node. It will have its own process Id:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- spawn((self(Self),
          format(&#39;My process id is ~w~n&#39;, [Self]))).
true.
My process id is 21421552@http://localhost:3060
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code to run in the process is passed as the first argument to &lt;code&gt;spawn&lt;/code&gt; and must be between brackets. An optional second argument will provide the process id to the caller:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- spawn((self(Self),
          format(&#39;My process id is ~w~n&#39;, [Self])),
         Pid).
My process id is 33869438@http://localhost:3060
Pid = &#39;33869438&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A third argument can be provided to pass options to control spawning. These include the ability to link processes, monitor them or register a name to identify it in a registry.&lt;/p&gt;

&lt;p&gt;Using the REPL we can define new rules and run them in processes, either by consulting a file, or entering them via &lt;code&gt;[user]&lt;/code&gt;. The following code will define the code for a &#39;ping&#39; server process:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;server :-
   receive({
     ping(Pid) -&amp;gt; Pid ! pong, server
   }).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This can be added to a file and loaded in the REPL with &lt;code&gt;consult&lt;/code&gt;, or it can be entered directly using &lt;code&gt;[user]&lt;/code&gt; (note the use of Ctrl+D to exit the user input):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on Node A 
?- [user].
|: server :-
|:   receive({
|:     ping(Pid) -&amp;gt; Pid ! pong, server
|:   }).
|: ^D
% user://1 compiled 0.01 sec, 1 clauses
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;server&lt;/code&gt; blocks receiving messages looking for a &lt;code&gt;ping(Pid)&lt;/code&gt; message. It sends a &lt;code&gt;pong&lt;/code&gt; message back to the process id it extracted from the message and calls itself recursively using a tail call. Run on the node with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node A
?- spawn((server), Pid).
Pid = &#39;18268992&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Send a message from another node by referencing the Pid along with the nodes address:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node B
?- self(Self), 18268992@&#39;http://localhost:3060&#39; ! ping(Self).
Self = thread(1)@&#39;http://localhost:30601.

?- flush.
% Got pong
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;flush&lt;/code&gt; call will remove all messages from the process&#39; queue and display them. In this case, the &lt;code&gt;pong&lt;/code&gt; reply from the other nodes server.&lt;/p&gt;

&lt;h2&gt;Spawning on remote nodes&lt;/h2&gt;

&lt;p&gt;Web Prolog provides the ability to spawn processes to run on remote nodes. This is done by passing a &lt;code&gt;node&lt;/code&gt; option to &lt;code&gt;spawn&lt;/code&gt;. To demonstrate, enter the following to create an &lt;code&gt;add&lt;/code&gt; rule in node A:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node A
?- [user].
|: add(X,Y,Z) :- Z is X + Y.
|: ^D
% user://1 compiled 0.01 sec, 1 clauses
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This creates an &#39;add&#39; predicate that works as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node A
?- add(1,2,Z).
Z = 3.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can call this predicate from node B by spawning a remote process that executes code in node A. In node B, it looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node B
?- self(Self),
   spawn((
     call(add(10, 20, Z)),
     Self ! Z
   ), Pid, [
     node(&#39;http://localhost:3060&#39;),
     monitor(true)
   ]),
   receive({ M -&amp;gt; format(&#39;Result is ~w~n&#39;, [M])})
Result is 30
Self = thread(1)@&#39;http://localhost:3061&#39;,
Pid = &#39;24931627&#39;@&#39;http://localhost:3060&#39;,
M = 30.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Passing &lt;code&gt;node&lt;/code&gt; as an option to &lt;code&gt;spawn/3&lt;/code&gt; results in a process being spawned on that referenced node and the code runs there. In the code we call the &lt;code&gt;add&lt;/code&gt; predicate that only exists on node A and return it by sending it to node B&#39;s identifier. The &lt;code&gt;monitor&lt;/code&gt; option provides status information about the remote process - including getting a message when the process exits. Calling &lt;code&gt;flush&lt;/code&gt; on node B shows that the process on node A exits:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on Node B
?- flush.
% Got down(&#39;24931627&#39;@&#39;http://localhost:3060&#39;,exit)
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the indirection in the &lt;code&gt;spawn&lt;/code&gt; call where &lt;code&gt;add&lt;/code&gt; isn&#39;t called directly, instead &lt;code&gt;call&lt;/code&gt; is used to call it. For some reason Web Prolog requires &lt;code&gt;add&lt;/code&gt; to exist on node B even though it is not called. The following gives an error on node B for example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node B
?- self(Self),
   spawn((
     add(10, 20, Z),
     Self ! Z
   ), Pid, [
     node(&#39;http://localhost:3060&#39;),
     monitor(true)
   ]),
   receive({ M -&amp;gt; format(&#39;Result is ~w~n&#39;, [M])})
ERROR: Undefined procedure: add/3 (DWIM could not correct goal)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&#39;m unsure if this is an error in web prolog or something I&#39;m doing.&lt;/p&gt;

&lt;h2&gt;RPC calls&lt;/h2&gt;

&lt;p&gt;The previous example can be simplified using RPC functions provided by web prolog. A synchronous RPC call from node B can be done that is aproximately equivalent to the above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- rpc(&#39;http://localhost:3060&#39;, add(1,2,Z)).
Z = 3.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or ansynchronously using promises:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- promise(&#39;http://localhost:3060&#39;, add(1,2,Z), Ref).
Ref = &#39;119435902516515459454946972679206500389&#39;.

?- yield($Ref, Answer).
Answer = success(anonymous, [add(1, 2, 3)], false),
Ref = &#39;119435902516515459454946972679206500389&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Upgrading a process&lt;/h2&gt;

&lt;p&gt;The following example, based on &lt;a href=&quot;https://bluishcoder.co.nz/2016/07/14/concurrency-in-wasp-lisp.html&quot;&gt;one I did for Wasp Lisp&lt;/a&gt;, is a process that maintains a count that can be incremented, decremented or retrieved:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;server(Count) :-
  receive({
    inc -&amp;gt; Count2 is Count + 1, server(Count2);
    dec -&amp;gt; Count2 is Count - 1, server(Count2);
    get(Pid) -&amp;gt; Pid ! value(Count), server(Count)
  }).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once defined, it can be spawned in node A with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- spawn((server(0)), Pid).
Pid = &#39;33403644&#39;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And called from Node B with code like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;?- self(Self), 33403644@&#39;http://localhost:3060&#39; ! get(Self).
Self = thread(1)@&#39;http://localhost:3061&#39;.

?- flush.
% Got value(0)
true.

?- 33403644@&#39;http://localhost:3060&#39; ! inc.
true.

?- self(Self), 33403644@&#39;http://localhost:3060&#39; ! get(Self).
Self = thread(1)@&#39;http://localhost:3061&#39;.

?- flush.
% Got value(1)
true.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can modify the server so it accepts an &lt;code&gt;upgrade&lt;/code&gt; message that contains the new code that the server will execute:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;server(Count) :-
  writeln(&quot;server receive&quot;),
  receive({
    inc -&amp;gt; Count2 is Count + 1, server(Count2);
    dec -&amp;gt; Count2 is Count - 1, server(Count2);
    get(Pid) -&amp;gt; Pid ! value(Count), server(Count);
    upgrade(Pred) -&amp;gt; writeln(&#39;upgrading...&#39;), call(Pred, Count)
  }).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run the server and send it some messages. Then define a &lt;code&gt;new_server&lt;/code&gt; on node A&#39;s REPL:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;new_server(Count) :-
  writeln(&quot;new_server receive&quot;),
  receive({
    inc -&amp;gt; Count2 is Count + 1, new_server(Count2);
    dec -&amp;gt; Count2 is Count - 1, new_server(Count2);
    mul(X) -&amp;gt; Count2 is Count * X, new_server(Count2);
    get(Pid) -&amp;gt; Pid ! value(Count), new_server(Count);
    upgrade(Pred) -&amp;gt; writeln(Pred), writeln(Count), call(Pred, Count)
  }).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And send an &lt;code&gt;upgrade&lt;/code&gt; message to the existing server:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# on node A
?- $Pid ! upgrade(new_server).
upgrading...
new_server receive
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the server understands the &lt;code&gt;mul&lt;/code&gt; message without having to be shut down and restarted.&lt;/p&gt;

&lt;h2&gt;Web IDE and tutorial&lt;/h2&gt;

&lt;p&gt;There&#39;s a web based IDE and tutorial based on &lt;a href=&quot;https://swish.swi-prolog.org/&quot;&gt;SWISH&lt;/a&gt;, the online SWI-Prolog system. To start this on a local node, run the following script from the web prolog source:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cd web-client
$ swipl run.pl
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now visit &lt;code&gt;http://localhost:3060/apps/swish/index.html&lt;/code&gt; in a web browser. This displays a tutorial on the left and a REPL on the right. Each loaded web page has its own namespace and local environment. You can send messages to and from individual web pages and the processes running in the local node. It uses websockets to send data to and from instances.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;There&#39;s a lot to the Web Prolog system and the implementation for SWI Prolog has some rough edges but it&#39;s usable to experiment with and get a feel for the system. I hope to write a more about some of the features of it, and SWI Prolog, as I get more familiar with it.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Capturing program invariants in ATS</title>
   <link href="http://bluishcoder.co.nz/2018/01/10/capturing-program-invariants-in-ats.html"/>
   <updated>2018-01-10T17:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2018/01/10/capturing-program-invariants-in-ats</id>
   <content type="html">&lt;p&gt;I&#39;ve been reading the book &lt;a href=&quot;https://www.cambridge.org/core/books/building-high-integrity-applications-with-spark/F213D9867D2E271F5FF3EDA765D48E95&quot;&gt;Building High Integrity Applications with Spark&lt;/a&gt; to learn more about the &lt;a href=&quot;https://en.wikipedia.org/wiki/SPARK_(programming_language)&quot;&gt;SPARK/Ada&lt;/a&gt; language for formal verification. It&#39;s a great book that goes through lots of examples of how to do proofs in Spark. I wrote a &lt;a href=&quot;http://bluishcoder.co.nz/2017/04/27/installing-gnat-and-spark-gpl-editions.html&quot;&gt;post on Spark/Ada&lt;/a&gt; earlier this year and tried some of the examples in the GNAT edition.&lt;/p&gt;

&lt;p&gt;While working through the book I oftened compared how I&#39;d implement similar examples in &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS&lt;/a&gt;. I&#39;ll go through one small example in this post and show how the dependent types of ATS allow capturing the invariants of a function and check them at type checking time to prove the absence of a particular class of runtime errors.&lt;/p&gt;

&lt;p&gt;The example I&#39;m looking at from the book is from the &lt;code&gt;Loop Invariants&lt;/code&gt; section, which aims to prove things about iterative loops in Ada. The procedure &lt;code&gt;Copy_Into&lt;/code&gt; copies characters from a &lt;code&gt;String&lt;/code&gt; into a &lt;code&gt;Buffer&lt;/code&gt; object that has a maximum capacity. If the source string is too short then the buffer is padded with spaces. The Spark/Ada code from the book is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;procedure Copy_Into(Buffer: out Buffer_Type; Source: in String) is
  Characters_To_Copy : Buffer_Count_type := Maximum_Buffer_Size;
begin
  Buffer := (others =&amp;gt; &#39; &#39;);
  if Source&#39;Length &amp;lt; Characters_To_Copy then
    Characters_To_Copy := Source`Length;
  end if;
  for Index in Buffer_Count_Type range 1 .. Characters_To_Copy loop
    pragma Loop_Invariant (Characters_To_Copy &amp;lt;= Source&#39;Length and
                           Characters_To_Copy = Characters_To_Copy&#39;Loop_Entry);
    Buffer(Index) := Source(Source&#39;First + (Index - 1));
  end loop;
end Copy_Into;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is quite readable for anyone familiar with imperative languages. The number of characters to copy is initially set to the maximum buffer size, then changed to the length of the string if it is less than that. The buffer is set to contain the initial characters &#39; &#39;. The buffer is 1-indexed and during the loop the characters from the string are copied to it.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Loop_Invariant&lt;/code&gt; pragma is a Spark statement that tells the checker that certain invariants should be true. The invariant used here is that the number of characters to copy is always less than or equal to the length of the string and does not change within the loop. Given this loop invariant Spark can assert that the indexing into the &lt;code&gt;Source&lt;/code&gt; string cannot exceed the bounds of the string. Spark is able to reason itself that &lt;code&gt;Buffer&lt;/code&gt; does not get indexed out of bounds as the loop ranges up to &lt;code&gt;Characters_To_Copy&lt;/code&gt; which is capped at &lt;code&gt;Maximum_Buffer_Size&lt;/code&gt;. I&#39;m not sure why this doesn&#39;t need a loop invariant but the book notes that the Spark tools improve over time at what invariants they can compute automatically. As an example, the second invariant check above for &lt;code&gt;Characters_To_Copy&#39;Loop_Entry&lt;/code&gt; isn&#39;t needed for newer versions of Spark but is kept to enable checking on older toolchains.&lt;/p&gt;

&lt;p&gt;For ATS I modeled the &lt;code&gt;Buffer&lt;/code&gt; type as an array of characters:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stadef s_max_buffer_size: int = 128
typedef Buffer0 = @[char?][s_max_buffer_size]
typedef Buffer1 = @[char][s_max_buffer_size]
val max_buffer_size: size_t s_max_buffer_size = i2sz(128)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In ATS, &lt;code&gt;@[char][128]&lt;/code&gt; represents an array of contiguous &#39;char&#39; types in memory, where those char&#39;s are initialized to value. The &lt;code&gt;@[char?][128]&lt;/code&gt; represents an array of unitialized char&#39;s. It would be a type error to use an element of that array before initializing it. The &#39;0&#39; and &#39;1&#39; suffixes to the &#39;Buffer&#39; name is an ATS idiom for uninitialized and initialized data respectively.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;stadef&lt;/code&gt; keyword creates a constant in the &#39;statics&#39; system of ATS. That is a constant in the language of types, vs a constant in the language of values where runtime level programming is done. For this post I have prefixed variables in the &#39;statics&#39; system with &lt;code&gt;s_&lt;/code&gt; to make it clearer where they can be used.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;max_buffer_size&lt;/code&gt; creates a constant in the &#39;dynamics&#39; part of ATS, in the language of values, of type &quot;&lt;code&gt;size_t max_buffer_size&lt;/code&gt;&quot;. &lt;code&gt;size_t&lt;/code&gt; is the type for indexes into arrays and &lt;code&gt;size_t 128&lt;/code&gt; is a dependent type representing a type where only a single value matches the type - &lt;code&gt;128&lt;/code&gt; in this instance. The &lt;code&gt;i2sz&lt;/code&gt; function converts an integer to a &lt;code&gt;size_t&lt;/code&gt;. So in this case we&#39;ve created a &lt;code&gt;max_buffer_size&lt;/code&gt; constant that can only ever be the same value as the &lt;code&gt;s_max_buffer_size&lt;/code&gt; type level constant.&lt;/p&gt;

&lt;p&gt;The ATS equivalent of &lt;code&gt;copy_into&lt;/code&gt; looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun copy_into {n:nat}
       (buffer: &amp;amp;Buffer0 &amp;gt;&amp;gt; Buffer1, source: string n): void = let
  val () = array_initize_elt(buffer, max_buffer_size, &#39; &#39;)
  val len = string1_length(source)
  stadef s_tocopy = min(s_max_buffer_size, n)
  val tocopy: size_t s_tocopy = min(max_buffer_size, len)
  fun loop {m:nat | m &amp;lt; s_tocopy } .&amp;lt;s_tocopy - m&amp;gt;.
        (buffer: &amp;amp;Buffer1, m: size_t m): void = let
    val () = buffer[m] := source[m]
  in
    if m &amp;lt; tocopy - 1 then loop(buffer, m+1)
  end
in
  if len &amp;gt; 0 then
    loop(buffer, i2sz(0))
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Starting with the function declaration:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun copy_into {n:nat}
       (buffer: &amp;amp;Buffer0 &amp;gt;&amp;gt; Buffer1, source: string n): void
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The items between the curly brackets, &lt;code&gt;{...}&lt;/code&gt;, are universal variables used for setting constraints on the function arguments. Between the round brackets, &lt;code&gt;(...)&lt;/code&gt;, are the function arguments. The return type is &lt;code&gt;void&lt;/code&gt;. The function takes two arguments, &lt;code&gt;buffer&lt;/code&gt; and &lt;code&gt;source&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;buffer&lt;/code&gt; is a reference type, represented by the &lt;code&gt;&amp;amp;&lt;/code&gt; in the type. This is similar to a reference argument in C++ or a pointer argument in C. It allows modification of the argument by the function. The &lt;code&gt;Buffer0 &amp;gt;&amp;gt; Buffer1&lt;/code&gt; means on entry to the function the type is &lt;code&gt;Buffer0&lt;/code&gt;, the uninitialized &lt;code&gt;char&lt;/code&gt; array described earlier, and on exit it will be a &lt;code&gt;Buffer1&lt;/code&gt;, an initialized char array. if the body of the function fails to initialize the elements of the array it will be a type error.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;source&lt;/code&gt; argument is a &lt;code&gt;string n&lt;/code&gt;, where &lt;code&gt;n&lt;/code&gt; is a type index for the length of the string. By using a dependently typed string here we can use it later in the function body to set some invariants.&lt;/p&gt;

&lt;p&gt;In the body of the function the call to &lt;code&gt;array_initize_elt&lt;/code&gt; sets each element of the array to the space character. This also has the effect of changing the type stored in the array from &lt;code&gt;char?&lt;/code&gt; to &lt;code&gt;char&lt;/code&gt;, and the array is now a valid &lt;code&gt;Buffer1&lt;/code&gt;. This matches the type change specified in the function declaration for the &lt;code&gt;buffer&lt;/code&gt; argument.&lt;/p&gt;

&lt;p&gt;The next three lines compute the number of characters to copy:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val len = string1_length(source)
stadef s_tocopy = min(s_max_buffer_size, n)
val tocopy: size_t s_tocopy = min(max_buffer_size, len)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The length of the string is obtained. The &lt;code&gt;string1_&lt;/code&gt; prefix to function names is an idiom to show that they operate on dependently typed strings. &lt;code&gt;string1_length&lt;/code&gt; will return the string length. It returns a dependently typed &lt;code&gt;size_t x&lt;/code&gt;, where &lt;code&gt;x&lt;/code&gt; is the length of the string. This means that calling &lt;code&gt;string_length&lt;/code&gt; not only returns the length of the string but it sets a constraint such that the type index of the result is equal to the type index of the string passed in. Here is the declaration of &lt;code&gt;string1_length&lt;/code&gt; from the prelude (with some additional annotations removed):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun string1_length {n:int} (x: string n): size_t n
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reuse of the &lt;code&gt;n&lt;/code&gt; in the argument and result type is what tells the compiler to set the constraint when it is called. This is important for the next two lines. These perform the same operation, once in the statics and once in the dynamics. That is, once at the type level and once at the runtime level. The &lt;code&gt;stadef&lt;/code&gt; sets a type level constant called &lt;code&gt;s_tocopy&lt;/code&gt; to be constrained to be the same as the minimum of the max buffer size and the type level string length, &lt;code&gt;n&lt;/code&gt;. The &lt;code&gt;val&lt;/code&gt; line sets the runtime variable to the same calculation but using the runtime length. These two lengths must much as a result of the call to &lt;code&gt;string1_length&lt;/code&gt; described earlier. The type of &lt;code&gt;tocopy&lt;/code&gt; ensures this by saying that it is the singleton type that can only be fulfilled by the value represented by &lt;code&gt;s_tocopy&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;ATS has looping constructs but it&#39;s idiomatic to use tail recursion instead of loops. It is also easier to create types for tail recursive functions than to type iterative loops in ATS. For this reason I&#39;ve converted the loop to a tail recursive function. When ATS compiles to C it converts tail recursive functions to a C loop so there is no danger of stack overflow. The looping function without dependent type annotations would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun loop (buffer: &amp;amp;Buffer1, m: size_t): void = let
  val () = buffer[m] := source[m]
in
  if m &amp;lt; tocopy - 1 then loop(buffer, m+1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It takes a &lt;code&gt;buffer&lt;/code&gt; and an index, &lt;code&gt;m&lt;/code&gt;, as arguments and assigns to &lt;code&gt;buffer&lt;/code&gt; at that index the equivalent entry from the &lt;code&gt;source&lt;/code&gt; string. If it hasn&#39;t yet copied the number of characters needed to copy it tail recursively calls itself, increasing the index. The initial call is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;loop(buffer, i2sz(0))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;i2sz&lt;/code&gt; is needed to convert the integer number zero from an &lt;code&gt;int&lt;/code&gt; type to a &lt;code&gt;size_t&lt;/code&gt; type.&lt;/p&gt;

&lt;p&gt;The declaration for the &lt;code&gt;loop&lt;/code&gt; function contains the dependent type definitions that give invariants similar to the Spark example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun loop {m:nat | m &amp;lt; s_tocopy } .&amp;lt;s_tocopy - m&amp;gt;.
      (buffer: &amp;amp;Buffer1, m: size_t m): void = let
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Starting with the arguments, the &lt;code&gt;buffer&lt;/code&gt; is a &lt;code&gt;Buffer&lt;/code&gt; meaning it must be an initialized array. The index, &lt;code&gt;m&lt;/code&gt; is a dependently typed &lt;code&gt;size_t m&lt;/code&gt; where &lt;code&gt;m&lt;/code&gt; at the type level is constrained to be less than the number of characters to copy. This ensures that the indexing into the buffer and source string is never out of bounds due to the previous statements that set &lt;code&gt;s_tocopy&lt;/code&gt; to be the lesser of the maximum buffer size and the string size. &lt;code&gt;s_tocopy&lt;/code&gt; is needed here instead of &lt;code&gt;tocopy&lt;/code&gt; due to universal arguments being written in the language of the typesystem, not the runtime system.&lt;/p&gt;

&lt;p&gt;The body of the loop does the copying of the indexed character from the source string to the buffer and recursively calls itself with an incremented index if it hasn&#39;t copied the required number of characters.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  val () = buffer[m] := source[m]
in
  if m &amp;lt; tocopy - 1 then loop(buffer, m+1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Due to the constraints set in the function declaration the buffer and source string indexes are checked at compile time to ensure they aren&#39;t out of bounds, and the recursive call to loop will fail typechecking if an out of bounds index is passed as an argument.&lt;/p&gt;

&lt;p&gt;One issue with recursive functions is that they could loop forever if the termination condition check is incorrect, or the variables being used in that check don&#39;t explicitly increase or decrease. In this case the index must increase to eventually reach the value for the termination check.&lt;/p&gt;

&lt;p&gt;ATS resolves this by allowing &lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/x2500.html&quot;&gt;termination metrics&lt;/a&gt; to be added to the function. This is the part of the function declaration that is bracketed by &lt;code&gt;.&amp;lt; ... &amp;gt;.&lt;/code&gt; markers. The expression inside these markers is expected to be in the &#39;statics&#39; constraint language and evaluate to a tuple of natural numbers that the compiler needs to prove are lexicographically decreasing in value. The &lt;code&gt;loop&lt;/code&gt; index counts up so this needs to be converted to a decreasing value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.&amp;lt;s_tocopy - m&amp;gt;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is done by taking the static constant of the number of characters to copy and subtracting the index value. The compiler proves that each recursive call in the body of the function results in something strictly less than the previous call. With the termination metric added it statically proves that the recursive function terminates.&lt;/p&gt;

&lt;p&gt;The program can be run and tested with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

stadef s_max_buffer_size: int = 128
typedef Buffer0 = @[char?][s_max_buffer_size]
typedef Buffer1 = @[char][s_max_buffer_size]
val max_buffer_size: size_t s_max_buffer_size = i2sz(128)

fun copy_into {n:nat}
    (buffer: &amp;amp;Buffer0 &amp;gt;&amp;gt; Buffer1, source: string n): void = let
  val () = array_initize_elt(buffer, max_buffer_size, &#39; &#39;)
  val len = string1_length(source)
  stadef s_tocopy = min(s_max_buffer_size, n)
  val tocopy: size_t s_tocopy = min(max_buffer_size, len)
  fun loop {m:nat | m &amp;lt; s_tocopy } .&amp;lt;s_tocopy - m&amp;gt;.
        (buffer: &amp;amp;Buffer1, m: size_t m): void = let
    val () = buffer[m] := source[m]
  in
    if m &amp;lt; tocopy - 1  then loop(buffer, m+1)
  end
in
  if len &amp;gt; 0 then
    loop(buffer, i2sz(0))
end 

implement main0() = let
  var  b = @[char?][max_buffer_size]()
  val () = copy_into(b, &quot;hello world&quot;)
  fun print_buffer {n:nat | n &amp;lt; s_max_buffer_size}
                   .&amp;lt;s_max_buffer_size - n&amp;gt;.
       (buffer: &amp;amp;Buffer1, n: size_t n):void = let
    val () = if n = 0 then print!(&quot;[&quot;)
    val () = print!(buffer[n])
    val () = if n = max_buffer_size - 1 then print!(&quot;]&quot;)
  in
    if n &amp;lt; 127 then print_buffer(buffer, n + 1)
  end
  val () = print_buffer(b, i2sz(0))
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example creates the array as a stack allocated object in the line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var  b = @[char?][max_buffer_size]()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Being stack allocated the memory will be deallocated on exit of the scope it was defined in. It&#39;s also possible to create a heap allocated buffer and pass that to &lt;code&gt;copy_into&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0() = let
  val (pf_b , pf_gc| b) = array_ptr_alloc&amp;lt;char&amp;gt;(max_buffer_size)
  val () = copy_into(!b, &quot;hello world&quot;)
  fun print_buffer {n:nat | n &amp;lt; 128} .&amp;lt;128 - n&amp;gt;. (buffer: &amp;amp;(@[char][128]), n: int n):void = let
    val () = if n = 0 then print!(&quot;[&quot;)
    val () = print!(buffer[n])
    val () = if n = 127 then print!(&quot;]&quot;)
  in
    if n &amp;lt; 127 then print_buffer(buffer, n + 1)
  end
  val () = print_buffer(!b, 0)
  val () = array_ptr_free(pf_b, pf_gc | b)
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This explicitly allocates the memory for the array using &lt;code&gt;array_ptr_alloc&lt;/code&gt; and dereferences it in the &lt;code&gt;copy_into&lt;/code&gt; call using the &#39;&lt;code&gt;!b&lt;/code&gt;&#39; syntax. Note that this array is later free&#39;d using &lt;code&gt;array_ptr_free&lt;/code&gt;. Not calling that to free the memory would be a compile error.&lt;/p&gt;

&lt;p&gt;Although this is a simple function it demonstrates a number of safety features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The destination buffer cannot indexed beyond its bounds.&lt;/li&gt;
&lt;li&gt;The source string cannot be indexed beyond its bounds.&lt;/li&gt;
&lt;li&gt;There can be no buffer overflow on writing to the destination buffer.&lt;/li&gt;
&lt;li&gt;There can be no uninitialized data in the buffer on function exit.&lt;/li&gt;
&lt;li&gt;The internal recursive call must terminate.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The book &lt;a href=&quot;https://www.cambridge.org/core/books/building-high-integrity-applications-with-spark/F213D9867D2E271F5FF3EDA765D48E95&quot;&gt;Building High Integrity Applications with Spark&lt;/a&gt; is a great book for learning Spark and also for learning about the sorts of proofs used in production applications using Spark/Ada. Apart from learning a bit about Spark it&#39;s also a good exercise to think about how similar safety checks can be implemented in your language of choice.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Writing basic proofs in ATS</title>
   <link href="http://bluishcoder.co.nz/2018/01/03/writing-basic-proofs-in-ats.html"/>
   <updated>2018-01-03T17:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2018/01/03/writing-basic-proofs-in-ats</id>
   <content type="html">&lt;p&gt;This post covers using the latest version of ATS, &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS 2&lt;/a&gt;, and goes through proving some basic algorithms. I&#39;ve written a couple of posts before on using proofs in ATS 1:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2013/07/01/constructing-proofs-with-dataprop-in-ats.html&quot;&gt;Constructing Proofs with dataprop in ATS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2012/10/04/implementing-a-stack-with-proofs-in-ats.html&quot;&gt;Implementing a stack with proofs in ATS&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Writing proofs in ATS is complicated by the fact that the dependent types and proof component of the language does not use the full ATS language. It uses a restricted subset of the language. When implementing a proof for something like the factorial function you can&#39;t write factorial in the type system in the same way as you write it in the runtime system. Factorial in the latter is written using a function but in the former it needs to be encoded as relations in dataprop or dataview definitions.&lt;/p&gt;

&lt;p&gt;Recent additions to ATS 2 have simplified the task of writing some proofs by enabling the constraint checking of ATS to be done by an external SMT solver rather than the built in solver. External solvers like &lt;a href=&quot;https://github.com/Z3Prover/z3&quot;&gt;Z3&lt;/a&gt; have more features than the builtin solver and can solve constraints that the ATS solver cannot. For example, non-linear constraints are not solveable by ATS directly but are by using Z3 as the solver.&lt;/p&gt;

&lt;p&gt;In this post I&#39;ll start by describing how to write proofs using &lt;a href=&quot;https://groups.google.com/d/msg/ats-lang-users/YzU5FL2utdk/Cr583a3KuAEJ&quot;&gt;quantified constraints&lt;/a&gt;. This is the easiest proof writing method in ATS but requires Z3 as the solver. Next I&#39;ll continue with Z3 as the solver but describe how to write proofs using Z3 without quantified constraints. Finally I&#39;ll go through writing the proofs by encoding the algorithm as relations in dataprop. This approach progressively goes from an easy, less intrusive to the code method, to more the more difficult system requiring threading proofs throughout the code.&lt;/p&gt;

&lt;h2&gt;Installing Z3&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/Z3Prover/z3&quot;&gt;Z3&lt;/a&gt; is the external solver used in the examples in this post. To install from the Z3 github on Linux:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/Z3Prover/z3
$ cd z3
$ mkdir build
$ cd build
$ cmake -G &quot;Unix Makefiles&quot; -DCMAKE_BUILD_TYPE=Release ../
$ make &amp;amp;&amp;amp; sudo make install
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Installing ATS&lt;/h2&gt;

&lt;p&gt;I used &lt;a href=&quot;http://www.ats-lang.org/Downloads.html&quot;&gt;ATS2-0.3.8&lt;/a&gt; for the examples in this post. There are various &lt;a href=&quot;https://github.com/ats-lang/ats-lang.github.io/tree/master/SCRIPT&quot;&gt;scripts for installing&lt;/a&gt; but to do install manually from the &lt;a href=&quot;https://github.com/githwxi/ATS-Postiats/&quot;&gt;git repository&lt;/a&gt; on an Ubuntu based system:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ sudo apt-get install build-essential libgmp-dev libgc-dev libjson-c-dev
$ git clone git://git.code.sf.net/p/ats2-lang/code ATS2
$ git clone https://github.com/githwxi/ATS-Postiats-contrib.git ATS2-contrib
$ export PATSHOME=`pwd`/ATS2
$ export PATSCONTRIB=`pwd`/ATS2-contrib
$ export PATH=$PATSHOME/bin:$PATH
$ (cd ATS2 &amp;amp;&amp;amp; ./configure &amp;amp;&amp;amp; make all)
$ (cd ATS2/contrib/ATS-extsolve &amp;amp;&amp;amp; make DATS_C)
$ (cd ATS2/contrib/ATS-extsolve-z3 &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f patsolve_z3 $PATSHOME/bin)
$ (cd ATS2/contrib/ATS-extsolve-smt2 &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f patsolve_smt2 $PATSHOME/bin)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Optionally you can install the various ATS backends for generating code in other languages:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ (cd ATS2/contrib/CATS-parsemit &amp;amp;&amp;amp; make all)
$ (cd ATS2/contrib/CATS-atscc2js &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f bin/atscc2js $PATSHOME/bin)
$ (cd ATS2/contrib/CATS-atscc2php &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f bin/atscc2php $PATSHOME/bin)
$ (cd ATS2/contrib/CATS-atscc2py3 &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f bin/atscc2py3 $PATSHOME/bin)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Add &lt;code&gt;PATSHOME&lt;/code&gt;, &lt;code&gt;PATSCONTRIB&lt;/code&gt; and the change to &lt;code&gt;PATH&lt;/code&gt; to &lt;code&gt;.bash-rc&lt;/code&gt;, &lt;code&gt;.profile&lt;/code&gt;, or some other system file to have these environment variables populated when starting a new shell.&lt;/p&gt;

&lt;h2&gt;Dependent Types&lt;/h2&gt;

&lt;p&gt;A function to add numbers in ATS can be proven correct using dependent types by specifying the expected result using dependently typed integers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun add_int {m,n:int} (a: int m, b: int n): int (m + n) = a + b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This won&#39;t compile if the implementation does anything but result in the addition of the two integers. The constraint language used in dependent types is a restricted subset of the ATS language. I wrote a bit about this in my post on &lt;a href=&quot;http://bluishcoder.co.nz/2010/09/01/dependent-types-in-ats.html&quot;&gt;dependent types in ATS&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following is an implementation of the factorial function without proofs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

fun fact (n: int): int =
  if n &amp;gt; 0 then n * fact(n- 1) else 1

implement main0() = let
  val r = fact(5)
in
  println!(&quot;5! = &quot;, r)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compile and run with something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o f0 f0.dats
$ ./f0
5! = 120
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To prove that the implementation of factorial is correct we need to specify what factorial is in the constraint language of ATS. Ideally we&#39;d like to write something like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n: nat} (n: int n): int (fact(n)) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This would check that the body of the function implements something that matches the result of &lt;code&gt;fact&lt;/code&gt;. Unfortunately the restricted constraint language of ATS doesn&#39;t allow implementing or using arbitary functions in the type definition.&lt;/p&gt;

&lt;h2&gt;Using Z3 as an external solver&lt;/h2&gt;

&lt;p&gt;By default ATS solves constraints using its built in constraint solver. It has a mechanism for using an external solver, in this case Z3. To type check the previous factorial example using Z3 use the following commands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patsopt -tc --constraint-export -d f0.dats |patsolve_z3 -i
Hello from [patsolve_z3]!
typechecking is finished successfully!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the change to use &lt;code&gt;patsopt&lt;/code&gt; instead of &lt;code&gt;patscc&lt;/code&gt;. The &lt;code&gt;-tc&lt;/code&gt; flag does the type checking phase only. &lt;code&gt;--constraint-export&lt;/code&gt; results in the constraints to be exported to &lt;code&gt;stdout&lt;/code&gt; which is piped to &lt;code&gt;patsolve_z3&lt;/code&gt;. That command invokes Z3 and checks the constraint results.&lt;/p&gt;

&lt;p&gt;Since the resulting program may contain code that ATS can&#39;t typecheck itself, to actually build the final executable we invoke &lt;code&gt;patscc&lt;/code&gt; with a command line option to disable type checking. It&#39;s important that the checking has succeeded through the external solver before doing this!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc --constraint-ignore -o f0 f0.dats
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Z3 and quantified constraints&lt;/h2&gt;

&lt;p&gt;Using Z3 with quantified constraints is a new feature of ATS and quite experimental. &lt;a href=&quot;https://groups.google.com/d/msg/ats-lang-users/YzU5FL2utdk/MWQdZYRbcHwJ&quot;&gt;Hongwei notes some issues&lt;/a&gt; due to different versions of Z3 that can cause problems. It is however an interesting approach to proofs with ATS so I include the process of using it here and hope it becomes more stable as it progresses.&lt;/p&gt;

&lt;p&gt;ATS provides the &lt;code&gt;stacst&lt;/code&gt; keyword to introduce a constant into the &#39;statics&#39; part of the type system. The &#39;statics&#39; is the restricted constraint language used when specifying types. There are some examples of &lt;code&gt;stacst&lt;/code&gt; usage in the prelude file &lt;a href=&quot;https://github.com/ats-lang/ATS-Postiats-release/blob/master/prelude/basics_pre.sats&quot;&gt;basics_pre.sats&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;stacst&lt;/code&gt; we can introduce a function in the statics system for factorial:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fact: int -&amp;gt; int
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the following code is valid:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): int (fact(n)) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;ATS doesn&#39;t know about &lt;code&gt;fact&lt;/code&gt; in the statics system, it only knows it&#39;s a function that takes an &lt;code&gt;int&lt;/code&gt; and returns an &lt;code&gt;int&lt;/code&gt;. With Z3 as the external solver we can extend ATS&#39; constraint knowledge by adding assertions to the Z3 solver engine using &lt;code&gt;$static_assert&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;praxi fact_base(): [fact(0) == 1] void
praxi fact_ind {n:int | n &amp;gt;= 1} (): [fact(n) == n * fact(n-1)] void
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The keyword &lt;code&gt;praxi&lt;/code&gt; is used for defining axioms, whereas &lt;code&gt;prfun&lt;/code&gt; is used for proof functions that need an implementation. This is currently not checked by the compiler but may be at some future time. From a documentation perspective using &lt;code&gt;praxi&lt;/code&gt; shows no plan to actually prove the axiom.&lt;/p&gt;

&lt;p&gt;The two axioms here will add to the proof store the facts about the factorial function. The first, &lt;code&gt;fact_base&lt;/code&gt;, asserts that the factorial of zero is one. The second asserts that for all &lt;code&gt;n&lt;/code&gt;, where &lt;code&gt;n&lt;/code&gt; is greater than or equal to &lt;code&gt;1&lt;/code&gt;, that the factorial of &lt;code&gt;n&lt;/code&gt; is equivalent to &lt;code&gt;n * fact (n - 1)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To add these facts to Z3&#39;s knowledge, use &lt;code&gt;$solver_assert&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:int | n &amp;gt;= 0} (n: int n): int (fact(n)) = let
  prval () = $solver_assert(fact_base)
  prval () = $solver_assert(fact_ind)
in
  if n = 0 then 1 else n * fact(n - 1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This typechecks successfully. Changing the implementation to be incorrect results in a failed typecheck. Unfortunately, as is often the case with experimental code, sometimes an incorrect implementation will hang Z3 causing it to consume large amounts of memory
as noted earlier.&lt;/p&gt;

&lt;p&gt;The implementation of &lt;code&gt;fact&lt;/code&gt; here closely mirrors the specification. The following is a tail recursive implementation of &lt;code&gt;fact&lt;/code&gt; that is also proved correct to the specification:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

stacst fact: int -&amp;gt; int

extern praxi fact_base(): [fact(0) == 1] unit_p
extern praxi fact_ind{n:pos}(): [fact(n)==n*fact(n-1)] unit_p

fun fact {n:nat} (n: int n): int (fact(n)) = let
  prval () = $solver_assert(fact_base)
  prval () = $solver_assert(fact_ind)

  fun loop {n,r:nat} (n: int n, r: int r): int (fact(n) * r) =
    if n &amp;gt; 0 then loop (n - 1, n * r) else r
in
  loop (n, 1)
end

implement main0() = let
  val r = fact(5)  
in
  println!(&quot;5! = &quot;, r)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was tested and built with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patsopt -tc --constraint-export -d f4.dats |patsolve_z3 -i
Hello from [patsolve_z3]!
typechecking is finished successfully!
$ patscc --constraint-ignore -o f4 f4.dats
./f4
5! = 120
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Z3 with threaded proofs&lt;/h2&gt;

&lt;p&gt;Another approach to using the external solver is not to add constraints to the Z3 store via &lt;code&gt;$solver_assert&lt;/code&gt; but instead call the axioms explicitly as proof functions threaded in the body of the function. This is &lt;code&gt;fact&lt;/code&gt; implemented in such a way:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fact: int -&amp;gt; int

extern praxi fact_base(): [fact(0) == 1] void
extern praxi fact_ind {n:int | n &amp;gt;= 1} (): [fact(n) == n * fact(n-1)] void

fun fact {n:nat} (n: int n): int (fact(n)) =
  if n &amp;gt; 0 then let
      prval () = fact_ind {n} ()
    in
      n * fact(n - 1)
    end
  else let
      prval () = fact_base()
     in
       1
     end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code  is more verbose due to needing to embed the &lt;code&gt;prval&lt;/code&gt; statements in a &lt;code&gt;let&lt;/code&gt; block but it doesn&#39;t suffer the Z3 incompatibility that the quantified constraint example did. An incorrect implementation will give an error from Z3.&lt;/p&gt;

&lt;p&gt;The equivalent tail recursive version is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): int (fact(n)) = let
  fun loop {n,r:nat} (n: int n, r: int r): int (fact(n) * r) =
    if n &amp;gt; 0 then let
        prval () = fact_ind {n} ()
      in
        loop (n - 1, n * r)
      end
    else let
        prval () = fact_base()
      in
        r + 1
      end
in
  loop (n, 1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Dataprops and Datatypes&lt;/h2&gt;

&lt;p&gt;It&#39;s still possible to write a verified version of factorial without using an external solver but the syntactic overhead is higher. The specification of &lt;code&gt;fact&lt;/code&gt; needs to be implemented as a relation using &lt;code&gt;dataprop&lt;/code&gt;. A &lt;code&gt;dataprop&lt;/code&gt; introduces a type for the proof system in much the same way as declaring a datatype in the runtime system of ATS. Proof objects constructed from this type exist only at proof checking time and are erased at runtime. They can be taken as proof arguments in functions or included in return values. Proof functions can also be written to use them.  In the &lt;a href=&quot;https://groups.google.com/d/msg/ats-lang-users/2C9sRsGP430/q3DKdpmPCgAJ&quot;&gt;words of Hongwei Xi&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;A prop is like a type; a value classified by a prop is often called a proof, which is dynamic but erased by the compiler. So while proofs are dynamic, there is no proof construction at run-time.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;For a comparison of the syntax of &lt;code&gt;dataprop&lt;/code&gt; and &lt;code&gt;datatype&lt;/code&gt;, here is a type for &quot;list of integers&quot; implement as both:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dataprop prop_list =
 | prop_nil
 | prop_cons of (int, prop_list)

datatype list =
 | list_nil
 | list_cons of (int, list)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To specifiy &lt;code&gt;fact&lt;/code&gt; as a relation it is useful to see how it is implemented in a logic based progamming language like Prolog:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fact(0, 1).
fact(N, R) :-
    N &amp;gt; 0,
    N1 is N - 1,
    fact(N1, R1),
    R is R1 * N.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The equivalent as a &lt;code&gt;dataprop&lt;/code&gt; is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dataprop FACT (int, int) =
  | FACTzero (0, 1)
  | {n,r1:int | n &amp;gt; 0} FACTsucc (n, r1 * n) of (FACT (n-1, r1))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;FACT(n,r)&lt;/code&gt; encodes the relation that &lt;code&gt;fact(n) = r&lt;/code&gt; where fact is defined as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;fact(0) = 1, and&lt;/li&gt;
&lt;li&gt;fact(n) where n &gt; 0 = n * fact(n - 1)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The &lt;code&gt;dataprop&lt;/code&gt; creates a &lt;code&gt;FACT(int, int)&lt;/code&gt; prop with two constructors:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;FACTzero()&lt;/code&gt; which encodes the relation that &lt;code&gt;fact(0) = 1&lt;/code&gt;, and&lt;/li&gt;
&lt;li&gt;&lt;code&gt;FACTsucc(FACT(n-1, r1))&lt;/code&gt; which encodes the relation that &lt;code&gt;fact(n) = n * fact(n-1)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The declaration of the &lt;code&gt;fact&lt;/code&gt; function uses this prop as a proof return value to enforce that the result must match this relation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The return value there is a tuple, where the first element is a proof value (the left of the pipe symbol) and the second element is the factorial result. The existential variable &lt;code&gt;[r:int]&lt;/code&gt; is used to associate the returned value with the result of the &lt;code&gt;FACT&lt;/code&gt; relation and the universal variable, &lt;code&gt;{n:nat}&lt;/code&gt; is used to provide the first argument of the fact prop. Through unification the compiler checks that the relationships between the variables match.&lt;/p&gt;

&lt;p&gt;The implementation of the function is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) =
  if n &amp;gt; 0 then let
    val (pf1 | r1) = fact (n - 1)
    val r = n * r1
  in
    (FACTsucc (pf1) | r)
  end else begin
    (FACTzero () | 1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that the result of the recursive call to &lt;code&gt;fact&lt;/code&gt; deconstructs the proof result into &lt;code&gt;pf1&lt;/code&gt; and the value into &lt;code&gt;r1&lt;/code&gt; and that proof is used in the result of the &lt;code&gt;FACTsucc&lt;/code&gt; constructor. Proofs are constructed like datatypes. For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;FACTsucc(FACTzero())&lt;/code&gt; is &lt;code&gt;fact(1)&lt;/code&gt; (the successor, or next factorial, from &lt;code&gt;fact(0)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;FACTsucc(FACTsucc(FACTzero()))&lt;/code&gt; is &lt;code&gt;fact(2)&lt;/code&gt;, etc.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;In this way it can be seen that a call to &lt;code&gt;fact(1)&lt;/code&gt; will hit the first branch of the &lt;code&gt;if&lt;/code&gt; condition which recursively calls &lt;code&gt;fact(0)&lt;/code&gt;. That hits the second branch of the conditional to return the prop &lt;code&gt;FACTzero()&lt;/code&gt;. On return back to the caller this is returned as  &lt;code&gt;FACTsucc(FACTzero())&lt;/code&gt;, giving our prop return type as &lt;code&gt;FACT(1, 1)&lt;/code&gt;. Plugging these values into the &lt;code&gt;n&lt;/code&gt; and &lt;code&gt;r&lt;/code&gt; of the return type for the &lt;code&gt;int r&lt;/code&gt; value means that value the function returns must be &lt;code&gt;1&lt;/code&gt; for the function to pass type checking.&lt;/p&gt;

&lt;p&gt;Although these proofs have syntactic overhead, the runtime overhead is nil. Proofs are erased after typechecking and only the factorial computation code remains. The full compilable program is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

dataprop FACT (int, int) =
  | FACTzero (0, 1)
  | {n,r1:int | n &amp;gt; 0} FACTsucc (n, r1 * n) of (FACT (n-1, r1))

fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) =
  if n &amp;gt; 0 then let
    val (pf1 | r1) = fact (n - 1)
    val r = n * r1
  in
    (FACTsucc (pf1) | r)
  end else begin
    (FACTzero () | 1)
end

implement main0() = let
  val (pf | r) = fact(5)
in
  println!(&quot;5! = &quot;, r)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To compile and run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o f8 f8.dats
$ ./f8
5! = 120
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A tail recursive implementation of &lt;code&gt;fact&lt;/code&gt; using dataprop that type checks is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) = let
  fun loop {r:int}{i:nat | i &amp;lt;= n}
           (pf: FACT(i, r) | n: int n, r: int r, i: int i):
           [r1:int] (FACT(n, r1) | int (r1)) =
    if n - i &amp;gt; 0 then
        loop (FACTsucc(pf) | n, (i + 1) * r, i + 1)
    else (pf | r)
in
  loop (FACTzero() | n, 1, 0)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because our dataprop is defined recursively based on successors to a previous factorial, and we can&#39;t get a predecessor, the tail recursive loop is structured to count up. This means we have to pass in the previous factorial prop as a proof argument, in &lt;code&gt;pf&lt;/code&gt;, and pass an index, &lt;code&gt;i&lt;/code&gt;, to be the current factorial being computed.&lt;/p&gt;

&lt;h2&gt;Fibonacci&lt;/h2&gt;

&lt;p&gt;Fibonacci is similar to factorial in the way the proofs are constructed. The quantified constraints versions is trivial:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fib: int -&amp;gt; int

extern praxi fib0(): [fib(0) == 0] unit_p
extern praxi fib1(): [fib(1) == 1] unit_p
extern praxi fib2 {n:nat|n &amp;gt;= 2} (): [fib(n) == fib(n-1) + fib(n-2)] unit_p

fun fib {n:int | n &amp;gt;= 0} (n: int n): int (fib(n)) = let
  prval () = $solver_assert(fib0)
  prval () = $solver_assert(fib1)
  prval () = $solver_assert(fib2)
in
  if n = 0 then 0
  else if n = 1 then 1
  else fib(n-1) + fib(n -2)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The threaded version using the external solver isn&#39;t much more verbose:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fib: int -&amp;gt; int

extern praxi fib0(): [fib(0) == 0] void
extern praxi fib1(): [fib(1) == 1] void
extern praxi fib2 {n:nat|n &amp;gt;= 2} (): [fib(n) == fib(n-1) + fib(n-2)] void

fun fib {n:int | n &amp;gt;= 0} (n: int n): int (fib(n)) =
  if n = 0 then let
      prval () = fib0()
    in
      0
    end
  else if n = 1 then let
      prval () = fib1()
    in
      1
    end
  else let
      prval () = fib2 {n} ()
    in
      fib(n-1) + fib(n -2)
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The dataprop version is quite readable too and has the advantage of not needing an external solver:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dataprop FIB (int, int) =
  | FIB0 (0, 0)
  | FIB1 (1, 1)
  | {n:nat}{r0,r1:int} FIB2(n, r1+r0) of (FIB(n-1, r0), FIB(n-2, r1))

fun fib {n:nat} (n: int n): [r:int] (FIB (n, r) | int r) =
  if n = 0 then (FIB0() | 0)
  else if n = 1 then (FIB1() | 1)
  else let
      val (pf0 | r0) = fib(n-1)
      val (pf1 | r1) = fib(n-2)
    in
      (FIB2(pf0, pf1) | r0 + r1)
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The dataprop maps nicely to the Prolog implementation of fibonacci:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fib(0,0).
fib(1,1).
fib(N,R) :- N1 is N-1, N2 is N-2, fib(N1,R1),fib(N2,R2),R is R1+R2.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I leave proving different implementations of &lt;code&gt;fib&lt;/code&gt; to the reader.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;There are more algorithms that could be demonstrated but this post is getting long. Some pointers to other interesting examples and articles on ATS and proofs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/jats-ug/practice-ats/tree/master/static_rps&quot;&gt;Rock, Paper, Scissors in the type system&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.slideshare.net/master_q/atslf-for-coq-users/6&quot;&gt;ATS/LF for Coq Users&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/HTMLTOC/c2867.html&quot;&gt;Theorem proving in ATS/LF&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/HTMLTOC/c3154.html&quot;&gt;Programming with Theorem proving&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/EXAMPLE/EFFECTIVATS/prop-logic/main.html&quot;&gt;Encoding Propositional Logic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/EXAMPLE/EFFECTIVATS/PwTP-bool-vs-prop/main.html&quot;&gt;Two styles of theorem proving in ATS&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;In general proof code adds a syntactic overhead to the code. With more work on using external solvers it looks like things will become easier with automated solving. ATS allows the programmer to write normal code and add proofs as needed so the barrier to entry to applying proofs is quite low, given suitable documentation and examples.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Casting in ATS</title>
   <link href="http://bluishcoder.co.nz/2018/01/02/casting-in-ats.html"/>
   <updated>2018-01-02T17:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2018/01/02/casting-in-ats</id>
   <content type="html">&lt;p&gt;The &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS programming language&lt;/a&gt; has a powerful type and proof system to enable safe construction of programs. Sometimes there is a need to cast a value from one type to another. ATS provides a feature that enables the programming to write their own rules specifying what can be cast. This becomes important when converting types from non-dependent typed values to dependantly typed values and dealing with conversion of proofs. This post goes through some common examples.&lt;/p&gt;

&lt;p&gt;A casting function is introduced using the keyword &lt;code&gt;castfn&lt;/code&gt;. It only has a declaration - there is no implementation or body of the casting function. From a value perspective there is no change to the actual value being cast, only to the type. It is effectively the identity function except for the type change. This means the cast is only allowed for types that are the same size, typically a machine word. There is no runtime overhead for using a casting function.&lt;/p&gt;

&lt;h2&gt;Standard Types&lt;/h2&gt;

&lt;p&gt;The following example ATS program attempts to add an integer to an unsigned integer value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

implement main0() = let
  val x: uint = 5u
  val y: int = x + 5
in
  println!(&quot;y=&quot;, y)
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This results in a type error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o c2 c2.dats
c2.dats: 133(line=6, offs=16) -- 138(line=6, offs=21):
         error(3): the symbol [+] cannot be resolved as no match is found.
c2.dats: 124(line=6, offs=7) -- 130(line=6, offs=13):
         error(3): the pattern cannot be given the ascribed type.
c2.dats: 124(line=6, offs=7) -- 130(line=6, offs=13):
         error(3): mismatch of static terms (tyleq):
The actual term is: S2Eerrexp()
The needed term is: S2Eapp(S2Ecst(g0int_t0ype); S2Eextkind(atstype_int))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is saying that the operator &lt;code&gt;+&lt;/code&gt; has no matching implementation for the types provided. It is expecting an &lt;code&gt;int&lt;/code&gt; but got something else.&lt;/p&gt;

&lt;p&gt;The addition operator requires the two arguments to be of the same type. A casting function can be added to cast the unsigned integer to an integer:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn int_of_uint(x: uint): int

implement main0() = let
  val x: uint = 5u
  val y: int = int_of_uint(x) + 5
in
  println!(&quot;y=&quot;, y)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This compiles and runs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o c3 c3.dats
$ ./c3
y=10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A &lt;code&gt;castfn&lt;/code&gt; looks very much like a &lt;code&gt;fun&lt;/code&gt; declaration. It requires the name of the casting function, the argument it expects and a return type. There is no implementation as mentioned earlier. The compiler will convert the type of the argument to that of the return type. Another example follows showing conversion to a floating point value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn double_of_uint(x: uint): double

implement main0() = let
  val x: uint = 5u
  val y: double = double_of_uint(x) + 5.0
in
  println!(&quot;y=&quot;, y)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;castfn&lt;/code&gt; can have any name but most of the ATS prelude follows a format of including the &#39;from&#39; and &#39;to&#39; types in the name.&lt;/p&gt;

&lt;h2&gt;Dependent Types&lt;/h2&gt;

&lt;p&gt;Conversion between dependently typed values and non-dependently typed values are a common use of casting functions. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val x: [n:int] size_t n = string1_length(&quot;hello&quot;)
val y: int = x + 1 // Error here, mismatch between dependent and non-dependent int
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The type of &lt;code&gt;x&lt;/code&gt; is dependently typed in that it has a type index of sort &lt;code&gt;int&lt;/code&gt; for the length of the string. It is also of type &lt;code&gt;size_t&lt;/code&gt; but the snippet expects an &lt;code&gt;int&lt;/code&gt;. A &lt;code&gt;castfn&lt;/code&gt; allows casing away the dependent type index and converting the type at the same time:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; #include &quot;share/atspre_define.hats&quot;
 #include &quot;share/atspre_staload.hats&quot;

 extern castfn int0_of_size1 {n:int} (x: size_t n): int

 implement main0() = let
   val x: [n:int] size_t n = string1_length(&quot;hello&quot;)
   val y: int = int0_of_size1(x) + 1
 in
   println!(&quot;y=&quot;, y)
 end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the use of the &#39;0&#39; and &#39;1&#39; suffixes used for the type names in the &lt;code&gt;castfn&lt;/code&gt;. This is an idiom in ATS naming where a &#39;0&#39; means not dependently typed and &#39;1&#39; means it has a dependent type.&lt;/p&gt;

&lt;p&gt;It&#39;s possible to go in the other direction, casting from a non-dependent typed value to a dependently type value. This is an example of code that won&#39;t compile and needs a cast:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val x: int = 5
val y: [n:int] size_t n = x
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This fails due to &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; being different types. Adding a cast function to convert the &lt;code&gt;int&lt;/code&gt; to a &lt;code&gt;size_t&lt;/code&gt; and including a type index will allow it to compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn size1_of_int0 (x: int): [n:int] size_t n

implement main0() = let
  val x: int = 5
  val y: [n:int] size_t n = size1_of_int0(x)
in
  println!(&quot;y=&quot;, y)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the &lt;code&gt;castfn&lt;/code&gt; adds an existential variable to the return type (the &#39;&lt;code&gt;[n:int]&lt;/code&gt;&#39; part) to attach a type index of &quot;unspecified integer value&#39; to the type.&lt;/p&gt;

&lt;p&gt;Another common use of casting functions is to convert different string types. A &lt;code&gt;string&lt;/code&gt; is a non dependently typed string and a &lt;code&gt;string1&lt;/code&gt; is a dependently typed string with the length of the string as a type index. For example, arguments on a command line are &lt;code&gt;string&lt;/code&gt;, but if a &lt;code&gt;string&lt;/code&gt; function is called on it then there is a type error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0(argc, argv) =
  if argc &amp;gt; 1 then let
      val s: string = argv[1]
      val n = string1_length(s)
    in
      ()
    end
  else
    ()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using a &lt;code&gt;castfn&lt;/code&gt; can convert the &lt;code&gt;string&lt;/code&gt; to a &lt;code&gt;string1&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn string1_of_string (s: string): [n:int] string n

implement main0(argc, argv) =
  if argc &amp;gt; 1 then let
      val s: string = argv[1]
      val n = string1_length(string1_of_string(s)) 
    in
      ()
    end
  else
    ()
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Casting linear types&lt;/h2&gt;

&lt;p&gt;Types can be cast to and from linear types. When programming with strings in ATS you often deal with &lt;code&gt;string&lt;/code&gt; which does not need to be manually free&#39;d and &lt;code&gt;strptr&lt;/code&gt; which is a linear type and needs to be manually free&#39;d. Sometimes you want to treat a &lt;code&gt;strptr&lt;/code&gt; as a &lt;code&gt;string&lt;/code&gt; to call a &lt;code&gt;string&lt;/code&gt; based function. An example is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern fun strdup(s: string): [l:addr] strptr l = &quot;ext#&quot;
extern castfn strptr_to_string {l:addr} (s: !strptr l): string

implement main0() = let
  val s: [l:addr] strptr l = strdup(&quot;hello world&quot;)
  val n = string0_length(strptr_to_string(s))
  val _ = strptr_free(s)
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example needs to be compiled passing &#39;&lt;code&gt;-DATS_MEMALLOC_LIBC&lt;/code&gt;&#39; to tell ATS to use the standard C malloc/free calls.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -DATS_MEMALLOC_LIBC -o c8 c8.dats
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the purposes of this example I use a FFI function to call the C &lt;code&gt;strdup&lt;/code&gt; function to copy a static string to a linear string that needs to be free&#39;d. Note that the &lt;code&gt;castfn&lt;/code&gt; does not consume this linear type (evidenced by the &#39;&lt;code&gt;!&lt;/code&gt;&#39; prefixing the type name in the argument). This is dangerous because we can store the return value of the cast and use it after the free:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val oops = strptr_to_string(s)
val _ = strptr_free(s)
val _ = println!(oops)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The danger can be restricted by using locally scoped cast functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val n = string0_length(strptr_to_string(s)) where {
          extern castfn strptr_to_string {l:addr} (s: !strptr l): string
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now &lt;code&gt;strptr_to_string&lt;/code&gt; can only be used within that local block of code. Cast functions can be dangerous so need some care. There are various prelude casting functions for performing these types of conversions already.&lt;/p&gt;

&lt;h2&gt;Prelude unsafe casts&lt;/h2&gt;

&lt;p&gt;The prelude has an &#39;unsafe&#39; module with a casting polymorphic function which can be used instead of defining casting functions for trivial things. There are also functions for converting &lt;code&gt;strptr&lt;/code&gt; to &lt;code&gt;string&lt;/code&gt;, etc. The equivalent of the previous example would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

staload UN = $UNSAFE

extern fun strdup(s: string): [l:agz] strptr l = &quot;ext#&quot;

implement main0() = let
  val s: [l:agz] strptr l = strdup(&quot;hello world&quot;)
  val n = string0_length($UN.strptr2string(s))
  val _ = strptr_free(s)
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Basic type casting can be done using the &lt;code&gt;cast&lt;/code&gt; function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

staload UN = $UNSAFE

implement main0() = let
  val x: uint = 5u
  val y: int = $UN.cast{int}(x) + 5
in
  println!(&quot;y=&quot;, y)
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The swiss army knife of unsafe casting functions are &lt;code&gt;castvwtp0&lt;/code&gt; and &lt;code&gt;castvwtp1&lt;/code&gt;. They can be used for casting linear types. The string example previously can use this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val s: [l:agz] strptr l = strdup(&quot;hello world&quot;)
val n = string0_length($UN.castvwtp1{string}(s))
val _ = strptr_free(s)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;castvwtp1&lt;/code&gt; will not consume the input argument whereas &lt;code&gt;castvwtp0&lt;/code&gt; will. Looking through the &lt;code&gt;prelude/SATS/unsafe.sats&lt;/code&gt; file will give an idea of the range of available functions.&lt;/p&gt;

&lt;p&gt;The examples in this post are somewhat contrived in that there are standard prelude functions for doing most everything already. The need to cast &lt;code&gt;string&lt;/code&gt; to &lt;code&gt;string1&lt;/code&gt; and &lt;code&gt;strptr&lt;/code&gt; are reduced due to specific functions being available for those types. However it is useful to learn to use the &lt;code&gt;castfn&lt;/code&gt; functionality and it is handy for one-off local casts, or defining protocols using proofs to ensure safe casting to and from types.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Cross Compiling ATS Programs</title>
   <link href="http://bluishcoder.co.nz/2017/12/02/cross-compiling-ats-programs.html"/>
   <updated>2017-12-02T23:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2017/12/02/cross-compiling-ats-programs</id>
   <content type="html">&lt;p&gt;A few years ago I wrote a mailing list post on &lt;a href=&quot;https://sourceforge.net/p/ats-lang/mailman/message/29036314/&quot;&gt;cross compiling ATS to Android&lt;/a&gt;. With &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS2&lt;/a&gt; being released the ability to cross compile has been made easier. In this post I&#39;ll show how to produce static linux binaries using &lt;a href=&quot;https://www.musl-libc.org/&quot;&gt;musl libc&lt;/a&gt; and how to build Android and Windows ATS programs by cross compiling on linux.&lt;/p&gt;

&lt;p&gt;For these examples I&#39;m using &lt;a href=&quot;http://www.ats-lang.org/Downloads.html&quot;&gt;ATS2-0.3.8&lt;/a&gt;. I&#39;ll use the simplest of &#39;Hello World&#39; programs in ATS to cross compile. The following is the contents of &lt;code&gt;hello.dats&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0() = print!(&quot;Hello World\n&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat hello.dats
implement main0() = print!(&quot;Hello World\n&quot;)

$ patscc -o hello hello.dats
$ ./hello
Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Static musl libc binaries&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://www.musl-libc.org/&quot;&gt;musl libc&lt;/a&gt; is a lightweight standard library for C programs. I use this instead of glibc because statically linked binaries using glibc have issues using networking functionality. There are no problems using networking routines with musl libc, it&#39;s smaller and lightweight and works well statically linked into executables. To build musl libc I used these steps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone git://git.musl-libc.org/musl
$ cd musl
$ ./configure
$ make
$ sudo make install
$ export PATH=$PATH:/usr/local/musl/bin/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The ATS compiler, &lt;code&gt;patscc&lt;/code&gt;, compiles ATS code to C. It defaults to using  &lt;code&gt;gcc&lt;/code&gt; but takes an &lt;code&gt;atsccomp&lt;/code&gt; command line argument to define an alternative C compiler to use for compiling the generated C code. Unknown command line arguments are passed directly to that C compiler. Given musl libc installed in &lt;code&gt;/usr/local/musl&lt;/code&gt; as above, a static binary can be built with &lt;code&gt;musl-gcc&lt;/code&gt; like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o hello -atsccomp &quot;/usr/local/musl/bin/musl-gcc&quot; -static \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I pass the &lt;code&gt;-static&lt;/code&gt; flag to produce a statically linked binary and two &lt;code&gt;-I&lt;/code&gt; include paths to find the ATS runtime. These appear to be required if &lt;code&gt;-atsccomp&lt;/code&gt; is used. In this case I use the environment variable &lt;code&gt;PATSHOME&lt;/code&gt; to find the installation directory of ATS. Hopefully that was set at ATS installation time. If this command succeeded then we have a static binary:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./hello
Hello World
$ ldd hello
not a dynamic executable
$ strip hello &amp;amp;&amp;amp; ls -l hello
-rwxr-xr-x 1 myuser myuser 18224 Dec  2 23:21 hello
$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Cross compiling Windows binaries&lt;/h2&gt;

&lt;p&gt;To build Windows compatible binaries on Linux I used &lt;a href=&quot;https://mingw-w64.org/doku.php&quot;&gt;mingw-w64&lt;/a&gt;. On Ubuntu this is available in the &lt;code&gt;gcc-mingw-w64&lt;/code&gt; package. With that installed a Windows &lt;code&gt;hello&lt;/code&gt; binary can be built with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; $ patscc -o hello.exe -atsccomp &quot;i686-w64-mingw-gcc&quot; \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
 $ file hello.exe
 hello.exe: PE32 executable (console) Intel 80386, for MS Windows
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Copying to a Windows machine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;C:\Users\Myuser&amp;gt; .\hello
Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Cross compiling Android binaries&lt;/h2&gt;

&lt;p&gt;To build on Android I generated a &lt;a href=&quot;https://developer.android.com/ndk/guides/standalone_toolchain.html&quot;&gt;standalone toolchain&lt;/a&gt; using the Android NDK. This produces standard command line compilers that generate Android compatible binaries. Install the &lt;a href=&quot;https://developer.android.com/ndk/downloads/index.html&quot;&gt;Android NDK&lt;/a&gt; - I used &lt;code&gt;android-ndk-r16&lt;/code&gt; - and run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ANDROID_NDK/build/tools/make-standalone-toolchain.sh \
  --arch=arm --install-dir=$STK_ROOT
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Replace &lt;code&gt;ANDROID_NDK&lt;/code&gt; with the path to the Android NDK and &lt;code&gt;STK_ROOT&lt;/code&gt; with the destination where you want the standalone toolchain installed. Use &lt;code&gt;arm64&lt;/code&gt; instead of &lt;code&gt;arm&lt;/code&gt; to build an ARM 64-bit binary.&lt;/p&gt;

&lt;p&gt;Now the &quot;Hello World&quot; program can be built using the C compiler from the standalone toolchain. To build on 32-bit using an &lt;code&gt;arm&lt;/code&gt; standalone toolchain, use &lt;code&gt;arm-linux-androideabi-clang&lt;/code&gt; as the C compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; $ patscc -o hello -atsccomp $STK_ROOT/bin/arm-linux-androideabi-clang \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
 $ file hello
 hello: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV),
        dynamically linked, interpreter /system/bin/linker, not stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To build on 64-bit ARM using an &lt;code&gt;arm64&lt;/code&gt; standalone toolchain, use &lt;code&gt;aarch64-linux-android-clang&lt;/code&gt; as the compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; $ patscc -o hello -atsccomp $STK_ROOT/bin/aarch64-linux-android-clang \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
 $ file hello
 hello64: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV),
          dynamically linked, interpreter /system/bin/linker64, not stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the use of &lt;code&gt;clang&lt;/code&gt; instead of &lt;code&gt;gcc&lt;/code&gt;. I believe &lt;code&gt;gcc&lt;/code&gt; support for building native Android executables with the NDK is deprecated - I got link errors when I tried.&lt;/p&gt;

&lt;p&gt;Copy the &lt;code&gt;hello&lt;/code&gt; executable to an Android phone. It needs to be somewhere writeable on the phone. On a recent non-rooted phone you should be able to use &lt;code&gt;/data/local/tmp&lt;/code&gt;. The following &lt;code&gt;adb&lt;/code&gt; commands work for me when the device is connected:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ adb push hello /data/local/tmp
$ adb shell
$ cd /data/local/tmp
$ chmod 0755 hello
$ ./hello
Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Producing an actual Android application would require using the ATS FFI to interface with the Android runtime - given the low level nature of ATS, if it can be done in C, it should be able to be done in ATS.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>ZeroMe - Decentralized Microblogging on ZeroNet</title>
   <link href="http://bluishcoder.co.nz/2017/10/12/zerome-decentralized-microblogging-on-zeronet.html"/>
   <updated>2017-10-12T21:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2017/10/12/zerome-decentralized-microblogging-on-zeronet</id>
   <content type="html">&lt;p&gt;I wrote about &lt;a href=&quot;https://zeronet.io/&quot;&gt;ZeroNet&lt;/a&gt; a few years ago when it was released and it mostly was about &lt;a href=&quot;http://bluishcoder.co.nz/2015/01/15/decentralized-websites-with-zeronet.html&quot;&gt;decentralized websites&lt;/a&gt;. In the time between then and now it has gained a lot of features and regular use. It still does distributed websites well but it adds features suchs as support for sharing large files, merging sites and distributed pseudo-anonymous identity. This post is about an application hosted on ZeroNet called &lt;code&gt;ZeroMe&lt;/code&gt;. It&#39;s a microblogging platform (i.e. A twitter like system) that takes advantage of ZeroNet&#39;s identity system and merging of sites.&lt;/p&gt;

&lt;h2&gt;Starting ZeroNet&lt;/h2&gt;

&lt;p&gt;To start with ZeroMe you first need to &lt;a href=&quot;https://github.com/HelloZeroNet/ZeroNet#user-content-how-to-join&quot;&gt;install ZeroNet&lt;/a&gt;. Given all the right dependancies are installed you can clone the github repository and run the Python script to get online:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/HelloZeroNet/ZeroNet
$ cd ZeroNet
$ ./zeronet.py
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will start the ZeroNet node and run a local webserver on port &lt;code&gt;43110&lt;/code&gt; to access it. This port is available on the local machine only. It also opens a port on &lt;code&gt;15441&lt;/code&gt; to communicate with other nodes. This port is open to the internet at large and will attempt to punch a hole through firewalls using UPNP.&lt;/p&gt;

&lt;p&gt;If you have the Tor daemon running then ZeroNet will connect to it and bridge between clearnet nodes and nodes running on Tor. You can force the node to run only on Tor by providing a command line argument:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./zeronet.py --tor always
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this configuration ZeroNet will not expose the port &lt;code&gt;15441&lt;/code&gt; over the internet. It will spawn Tor onion services and expose the port to those for communication with other ZeroNet nodes running on onion services. Access to the local node is still done via port &lt;code&gt;43110&lt;/code&gt; but you should use a browser configured to use Tor if anonymity is a concern since sites can run arbitary JavaScript. The main ZeroNet &#39;Hello&#39; page warns you if you are not using Tor Browser in this configuration.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet1.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet1.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Gaining an identity&lt;/h2&gt;

&lt;p&gt;ZeroMe requires an identity to be created. Identities are created through identity ZeroNet sites. The main one, operated by the creator of ZeroNet, is &lt;code&gt;ZeroId&lt;/code&gt;. When you first use a site that requires an identity you will be prompted to create one from any identity providers you have access to. For this example I&#39;ll use &lt;code&gt;ZeroId&lt;/code&gt;, accessible at &lt;code&gt;zeroid.bit&lt;/code&gt; - &lt;code&gt;http://localhost:43110/zeroid.bit&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet2.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet2.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click &lt;code&gt;Get auth cert&lt;/code&gt; and choose a username. There are two ways to make the request for the identity. The first is a request over the internet via HTTP. If you&#39;re not running the browser over Tor this will expose your IP address to the identity service. The other is using &lt;a href=&quot;https://bitmessage.org/wiki/Main_Page&quot;&gt;BitMessage&lt;/a&gt;, which is an anonymous messaging system. &lt;code&gt;ZeroId&lt;/code&gt; will request that you send a confirmation message to a &lt;code&gt;BitMessage&lt;/code&gt; address.&lt;/p&gt;

&lt;p&gt;This may seem very centralized - it requires the identity service to be running, if it goes down you can&#39;t create a new identity. There are other identity services on ZeroNet that have different requirements for creating an identity. And there&#39;s an API to create your own. Identities created using these work on any service using the ZeroNet identity API in the same was as &lt;code&gt;ZeroId&lt;/code&gt; identities.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ZeroId&lt;/code&gt; site will show your identity name once you&#39;ve signed up:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet3.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet3.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From &lt;code&gt;ZeroId&lt;/code&gt; you can search for existing users and choose to &lt;code&gt;Mute&lt;/code&gt; or &lt;code&gt;Unmute&lt;/code&gt;. By muting a particular identity you won&#39;t see any posts from that identity. This is useful for dealing with spam or users posting on topics you don&#39;t want to see. This will prevent you seeing their content on any ZeroNet site.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet4.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet4.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can manage muted users from the &lt;code&gt;Hello&lt;/code&gt; page left sidebar menu:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet15.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet15.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Joining a ZeroMe Hub&lt;/h2&gt;

&lt;p&gt;Access &lt;code&gt;ZeroMe&lt;/code&gt; by activating the &lt;code&gt;ZeroMe&lt;/code&gt; icon on the main user interface or going directly to &lt;code&gt;Me.ZeroNetwork.bit&lt;/code&gt; - http://localhost:43110/Me.ZeroNetwork.bit/&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet5.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet5.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A prompt on the top right asks you to accept a merger site. Merge sites are a way to split large sites into a number of smaller ones. You should approve this request.&lt;/p&gt;

&lt;p&gt;Click on &quot;Select user to post new content&quot; to create a &lt;code&gt;ZeroMe&lt;/code&gt; user. It will prompt for an identity to choose and you can select the one already created in &lt;code&gt;ZeroId&lt;/code&gt; above.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet6.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet6.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once an identity is chosen you&#39;ll be asked to select a &#39;hub&#39;. &lt;code&gt;ZeroMe&lt;/code&gt; works by having the user interface operate from the main &lt;code&gt;ZeroMe&lt;/code&gt; site with data on users and posts stored in &#39;Hub&#39; sites. You only see posts from users that belong to hubs that you have requested. There is a hub operated by the &lt;code&gt;ZeroMe&lt;/code&gt; creator and it will be shown as &lt;code&gt;Sun hub&lt;/code&gt; on this page along with any other Hub sites you may already have requested. Click &lt;code&gt;Download&lt;/code&gt; on a hub to download existing posts and content for that hub and &lt;code&gt;Join&lt;/code&gt; to join one.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet7.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet7.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Downloading a hub can take some time. On the &lt;code&gt;Hello&lt;/code&gt; ZeroNet page you can see the progress of any sites currently being downloaded.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet8.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet8.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There&#39;s a useful site called &lt;code&gt;0hub.bit&lt;/code&gt; that lists known hubs and lets you download them all. It&#39;s at &lt;code&gt;http://localhost:43110/0hub.bit/&lt;/code&gt; and clicking the &lt;code&gt;Click me to unlock all hub post in ZeroNet&lt;/code&gt; will start downloading them. This takes some time but is worth it since you can then see all posts by everyone on &lt;code&gt;ZeroMe&lt;/code&gt;. You can delete hubs if you decide you don&#39;t want to see content from a particular hub.&lt;/p&gt;

&lt;h2&gt;Microblogging with ZeroMe&lt;/h2&gt;

&lt;p&gt;Now that you&#39;ve got an identity, signed into ZeroNet and joined a hub you can starting reading content and posting. The &lt;code&gt;Everyone&lt;/code&gt; tab in the user interface will show posts from all users, even those you haven&#39;t followed. This is useful at the beginning to find users and content.&lt;/p&gt;

&lt;p&gt;Posts are in Markdown format and can include images. There is no limit to the size of a post and posts can have comments. You can visit profile pages of users and choose to optionally seed their images, mute users, and edit parts of your own profile page to have an avatar and description:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet12.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet12.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;An example of a post with comments (selected randomly, identities blacked out):&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet13.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet13.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Random stuff&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;ZeroNet&lt;/code&gt; node running on your machine enforces size limits for sites. This prevents sites that you have accessed from consuming all your disk space. When a site starts reaching the size limit it appears in the main &lt;code&gt;Hello&lt;/code&gt; page left sidebar in a special section:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet9.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet9.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the site goes past the limit it will no longer download updates. Visiting the site will give a popup asking to increase the limit. Approving that popup will resume downloads for the site until it hits the next limit.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet10.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet10.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There&#39;s a sidebar on the right of pages that can be accessed by dragging the top right &lt;code&gt;0&lt;/code&gt; icon to the left:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet11.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet11.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This sidebar gives statistics on the number of nodes seeding the site, the size limit, and various other things.&lt;/p&gt;

&lt;p&gt;When you visit a ZeroNet site you starting seeding that sites content and receive automatic updates when the content changes. This can be disabled on the main &lt;code&gt;Hello&lt;/code&gt; page on a per site basis. Sites can have &quot;optional files&quot; which you don&#39;t automatically seed. They are downloaded on demand and are often used for user generated content or larger files. You can choose to seed a sites optional files in the right hand sidebar for that site. There are also &quot;Big Files&quot; which are treated specially. These are large files like videos and are also optionally seeded. The &lt;code&gt;Files&lt;/code&gt; tab of the &lt;code&gt;Hello&lt;/code&gt; page lists optional and big files that you are seeding:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet14.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet14.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Sites can be set to allow cloning by end users. This creates a copy of the site with no content. An example of a site that does this is &lt;code&gt;ZeroBlog&lt;/code&gt; which you can clone to create your own blog. This extends to &lt;code&gt;ZeroMet&lt;/code&gt; itself. You can clone the &lt;code&gt;ZeroMe&lt;/code&gt; user interface site and modify that to get a customized look but it still uses the data from the existing hubs.&lt;/p&gt;

&lt;p&gt;There&#39;s a bunch of other interesting sites on ZeroNet. The &lt;code&gt;ZeroTalk&lt;/code&gt; forums, various blogs, &lt;code&gt;ZeroMail&lt;/code&gt; for encrypted email like service, etc. Be aware that the psuedo-anonymous use of identities can make for content you might not agree with and much spam. Use of &#39;Mute&#39; is useful here.&lt;/p&gt;

&lt;p&gt;Also be aware that it is &#39;psuedo-anonymous&#39; not &#39;anonymous&#39;. You create an identity and that identity is not tied to you in the real world but people can track what you do to that identity. Content is added to sites and distributed to other nodes. If you &lt;code&gt;like&lt;/code&gt; a post or add content to some site then anyone who decides to dig into the data of that site can see that your identity liked or posted that content. It is possible to have multiple identities if you want to keep aspects of your ZeroNet usage separate but that&#39;s a topic for another post.&lt;/p&gt;

&lt;p&gt;Overall ZeroMe is a nice microblogging system. It&#39;s user friendly, has a nice design and has tools for muting and &quot;Non Real Name&quot; identities. It, along with ZeroNet, is actively developed and supported by the ZeroNet developer.&lt;/p&gt;
</content>
 </entry>
 
 
</feed>
