From 960d0a7945920d6183e8f41557e07f41b4cc6e07 Mon Sep 17 00:00:00 2001 From: Eduardo Julian Date: Wed, 5 Apr 2017 19:23:44 -0400 Subject: - Added binary and hexadecimal syntax for degs. --- stdlib/source/lux/data/number.lux | 42 +++++++++++++++++++++++++++++++++--- stdlib/test/test/lux/data/number.lux | 10 +++++---- 2 files changed, 45 insertions(+), 7 deletions(-) (limited to 'stdlib') diff --git a/stdlib/source/lux/data/number.lux b/stdlib/source/lux/data/number.lux index a854e8bf7..7077ce70c 100644 --- a/stdlib/source/lux/data/number.lux +++ b/stdlib/source/lux/data/number.lux @@ -273,10 +273,46 @@ (#;Right (i.* sign output))))) (#;Left )))))] - [Binary@Codec 2 "01" "Invalid binary syntax."] - [Octal@Codec 8 "01234567" "Invalid octal syntax."] + [Binary@Codec 2 "01" "Invalid binary syntax: "] + [Octal@Codec 8 "01234567" "Invalid octal syntax: "] [_ 10 "0123456789" "Invalid syntax for Int: "] - [Hex@Codec 16 "0123456789ABCDEF" "Invalid hexadecimal syntax."] + [Hex@Codec 16 "0123456789ABCDEF" "Invalid hexadecimal syntax: "] + ) + +(def: (de-prefix input) + (-> Text Text) + (assume (_lux_proc ["text" "clip"] [input +1 (_lux_proc ["text" "size"] [input])]))) + +(do-template [ ] + [(struct: #export (Codec Text Deg) + (def: (encode value) + (let [raw-output (de-prefix (:: encode (:! Nat value))) + max-num-chars (n./ +64) + raw-size (_lux_proc ["text" "size"] [raw-output]) + zero-padding (loop [zeroes-left (n.- raw-size max-num-chars) + output ""] + (if (n.= +0 zeroes-left) + output + (recur (n.dec zeroes-left) + (_lux_proc ["text" "append"] ["0" output])))) + padded-output (_lux_proc ["text" "append"] [zero-padding raw-output])] + (_lux_proc ["text" "append"] ["." padded-output]))) + + (def: (decode repr) + (let [repr-size (_lux_proc ["text" "size"] [repr])] + (if (n.>= +2 repr-size) + (case (_lux_proc ["text" "char"] [repr +0]) + (^=> (#;Some #".") + [(:: decode (_lux_proc ["text" "append"] ["+" (de-prefix repr)])) + (#;Some output)]) + (#;Some (:! Deg output)) + + _ + (#;Left (_lux_proc ["text" "append"] [ repr]))) + (#;Left (_lux_proc ["text" "append"] [ repr]))))))] + + [Binary@Codec Binary@Codec +1 "Invalid binary syntax: "] + [Hex@Codec Hex@Codec +4 "Invalid hexadecimal syntax: "] ) (do-template [ ] diff --git a/stdlib/test/test/lux/data/number.lux b/stdlib/test/test/lux/data/number.lux index 8e959cf6f..eb09eec09 100644 --- a/stdlib/test/test/lux/data/number.lux +++ b/stdlib/test/test/lux/data/number.lux @@ -124,15 +124,17 @@ ["Nat/Binary" R;nat Eq Binary@Codec] ["Nat/Octal" R;nat Eq Octal@Codec] - ["Nat" R;nat Eq Codec] + ["Nat" R;nat Eq Codec] ["Nat/Hex" R;nat Eq Hex@Codec] ["Int/Binary" R;int Eq Binary@Codec] ["Int/Octal" R;int Eq Octal@Codec] - ["Int" R;int Eq Codec] + ["Int" R;int Eq Codec] ["Int/Hex" R;int Eq Hex@Codec] - ["Deg" R;deg Eq Codec] + ["Deg/Binary" R;deg Eq Binary@Codec] + ["Deg" R;deg Eq Codec] + ["Deg/Hex" R;deg Eq Hex@Codec] - ["Real" R;real Eq Codec] + ["Real" R;real Eq Codec] ) -- cgit v1.2.3