Last active
October 5, 2018 21:00
-
-
Save jrfondren/390e9deaeb2de731e835c855a63d3f65 to your computer and use it in GitHub Desktop.
ML-style datatypes in Zig and ATS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "share/atspre_staload.hats" | |
typedef amount = Nat | |
typedef ccn = $extype "int64_t" | |
typedef cvc = [i:nat | i < 9999] int(i) | |
datatype payment = | |
| card of (string, ccn, cvc, amount) | |
| paypal of (string, amount) | |
| cash of (amount) | |
implement fprint_val<ccn>(out, n) = () where { | |
val _ = $extfcall(int, "printf", "%lld", n) | |
} | |
fun print_ccn(n: ccn): void = fprint_val<ccn>(stdout_ref, n) | |
overload print with print_ccn | |
extern castfn int2ccn: Int -> ccn | |
fun print_payment(p: payment): void = | |
case+ p of | |
| card(name, ccn, cvc, amount) => | |
println!("Amount=", amount, " from Card(name=", name, ", ccn=", ccn, ", cvc=", cvc, ")") | |
| cash(amount) => | |
println!("Amount=", amount, " from Cash") | |
| paypal(email, amount) => | |
println!("Amount=", amount, " from Paypal(email=", email, ")") | |
implement main0() = | |
let | |
val p1 = card("Bob McBob", int2ccn(1234123412341234), 1234, 100) | |
val p2 = cash(200) | |
in | |
print_payment(p1); | |
print_payment(p2); | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const warn = std.debug.warn; | |
const PaymentCard = struct { | |
ccn: u64, | |
cvc: u16, | |
name: []const u8, | |
amount: u32, | |
}; | |
const PaymentPaypal = struct { | |
email: []const u8, | |
amount: u32, | |
}; | |
const PaymentCash = struct { | |
amount: u32, | |
}; | |
const Payments = enum { card, paypal, cash }; | |
const Payment = union(enum) { | |
card: PaymentCard, | |
paypal: PaymentPaypal, | |
cash: PaymentCash, | |
}; | |
fn print_payment(p: Payment) void { | |
switch (p) { | |
Payment.card => |card| { | |
warn("Amount={} from Card(name={}, ccn={}, cvc={})\n", | |
card.amount, card.name, card.ccn, card.cvc); | |
}, | |
Payment.cash => |cash| { | |
warn("Amount={} from Cash\n", cash.amount); | |
}, | |
Payment.paypal => |paypal| { | |
warn("Amount={} from Paypal(email={})\n", paypal.amount, paypal.email); | |
}, | |
} | |
} | |
pub fn main() void { | |
var p1 = Payment { .card = PaymentCard { .name = "Bob McBob",.ccn = 1234123412341234, .cvc = 1234, .amount = 100 } }; | |
var p2 = Payment { .cash = PaymentCash { .amount = 200 } }; | |
print_payment(p1); | |
print_payment(p2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment