SMAC
Friday, October 27, 2023
Recently, I was looking into the Zig programming language and bumped into this video tutorial:
It presents an example – in the spirit of Fizz
buzz – called SMAC, which is
basically a program that converts the first million numbers into strings or
"SMAC"
(if the number is divisible by 7 or ends with a 7) and prints them
out. This is then implemented in three different forms:
- single-threaded
- multi-threaded, and
- networked using sockets.
We first start with the basics, a word to check if a number is SMAC or not:
: smac? ( n -- ? )
{ [ 7 mod 0 = ] [ 10 mod 7 = ] } 1|| ;
And then a word that converts a number into its string representation or SMAC:
: smac ( n -- str )
dup smac? [ drop "SMAC" ] [ number>string ] if ;
Single-Threaded
The simplest example – run in a single-thread – iteratively prints to the output-stream.
: smac. ( n -- )
[1..b] [ smac print ] each ;
Trying it out, you can see that it works:
IN: scratchpad 20 smac.
1
2
3
4
5
6
SMAC
8
9
10
11
12
13
SMAC
15
16
SMAC
18
19
20
Multi-Threaded
Slightly more complex, the multi-threaded example splits the numbers into four n-groups, computes them as a future in four background threads, and then waits for those computations to finish and iteratively prints them out.
: smac. ( n -- )
[1..b] 4 <n-groups>
[ '[ _ [ smac ] map ] future ] map
[ ?future [ print ] each ] each ;
It produces the same output as the single-threaded smac.
word above.
Networked
The simple networked example creates a server configured to print n
results
when a client connects:
: smac-server ( n -- server )
utf8 <threaded-server>
"smac" >>name
7979 >>insecure
swap '[ _ smac. ] >>handler ;
You can run it:
IN: scratchpad 20 smac-server start-server
And then try it out:
$ nc localhost 7979
1
2
3
4
5
6
SMAC
8
9
10
11
12
13
SMAC
15
16
SMAC
18
19
20
A fun example for learning about a few introductory concepts in Factor!