Skip to content

Instantly share code, notes, and snippets.

@Capital-EX
Created July 3, 2024 18:25
Show Gist options
  • Save Capital-EX/7d21c3871b9cbb6964039a56c327b261 to your computer and use it in GitHub Desktop.
Save Capital-EX/7d21c3871b9cbb6964039a56c327b261 to your computer and use it in GitHub Desktop.
module(guessing-game.main)
import(std.prelude)
import(std.world)
import(std.maybe)
import(std.buffer)
external(libc-rand -> rand [+World -- +World CInt])
external(random-seed -> random_seed [+World -- +World],
"#include <stdlib.h>"
"#include <time.h>"
"void random_seed() { srand(time(NULL)); }"
)
data(+ScanfResult, +ScanfResult -> CPtr(CInt))
def(+ScanfResult.rdrop, +ScanfResult -- , +ScanfResult -> drop)
def(+ScanfResult.unwrap, +ScanfResult -- Int, +ScanfResult -> >Ptr unsafe(@I32) >Int)
external(scan_int [+World +n:+ScanfResult -- +World +n:+ScanfResult CInt],
"#include <stdio.h>"
"int scan_int(int* n){ return scanf(\"%d\", n); }"
)
# Do some dark magic
def scan-int [+World -- +World Maybe(Int)] {
256 >Size +Buffer.new base CPtr +ScanfResult >+n
rdip(scan_int) >Int 1 == if(+n> unwrap Some, +n> rdrop None) rdrop
}
def prompt [+World -- +World] {
"Enter Guess: " print-
}
def read-guess [+World -- +World Int] {
scan-int match {
{Some ->}
{None -> "Couldn't read number" print read-guess}
}
}
def pick-number [+World -- +World Int] {
random-seed libc-rand >Int 100 % 1 +
}
def play-game [+World Int -- +World] {
prompt read-guess over compare match {
{ LT -> "Too Low!" print play-game }
{ EQ -> "You Win!" print drop }
{ GT -> "Too High!" print play-game }
}
}
def main [+World -- +World] {
"I'm thinking of a number from 1 to 100..." print
pick-number
play-game
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment