Merge pull request #938 from paultag/paultag/feature/hex-and-octel
Add hex and octel support to Hy integers
This commit is contained in:
commit
456f33eb7c
@ -31,6 +31,21 @@ languages.
|
|||||||
that symbols with dashes will shadow their underscore equivalents, and vice
|
that symbols with dashes will shadow their underscore equivalents, and vice
|
||||||
versa.
|
versa.
|
||||||
|
|
||||||
|
Notes on Syntax
|
||||||
|
===============
|
||||||
|
|
||||||
|
integers
|
||||||
|
--------
|
||||||
|
|
||||||
|
.. versionadded:: 0.11.1
|
||||||
|
|
||||||
|
In addition to regular numbers, standard notation from Python 3 for non-base 10
|
||||||
|
integers is used. ``0x`` for Hex, ``0o`` for Octal, ``0b`` for Binary.
|
||||||
|
|
||||||
|
.. code-block:: clj
|
||||||
|
|
||||||
|
(print 0x80 0b11101 0o102 30)
|
||||||
|
|
||||||
|
|
||||||
Built-Ins
|
Built-Ins
|
||||||
=========
|
=========
|
||||||
|
@ -19,7 +19,7 @@
|
|||||||
# DEALINGS IN THE SOFTWARE.
|
# DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
from hy.models import HyObject, _wrappers
|
from hy.models import HyObject, _wrappers
|
||||||
from hy._compat import long_type
|
from hy._compat import long_type, str_type
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
@ -32,7 +32,19 @@ class HyInteger(HyObject, long_type):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __new__(cls, number, *args, **kwargs):
|
def __new__(cls, number, *args, **kwargs):
|
||||||
number = long_type(number)
|
if isinstance(number, str_type):
|
||||||
|
bases = {"0x": 16, "0o": 8, "0b": 2}
|
||||||
|
for leader, base in bases.items():
|
||||||
|
if number.startswith(leader):
|
||||||
|
# We've got a string, known leader, set base.
|
||||||
|
number = long_type(number, base=base)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# We've got a string, no known leader; base 10.
|
||||||
|
number = long_type(number, base=10)
|
||||||
|
else:
|
||||||
|
# We've got a non-string; convert straight.
|
||||||
|
number = long_type(number)
|
||||||
return super(HyInteger, cls).__new__(cls, number)
|
return super(HyInteger, cls).__new__(cls, number)
|
||||||
|
|
||||||
|
|
||||||
|
@ -12,6 +12,21 @@
|
|||||||
(assert (isinstance sys.argv list)))
|
(assert (isinstance sys.argv list)))
|
||||||
|
|
||||||
|
|
||||||
|
(defn test-hex []
|
||||||
|
"NATIVE: test hex"
|
||||||
|
(assert (= 0x80 128)))
|
||||||
|
|
||||||
|
|
||||||
|
(defn test-octal []
|
||||||
|
"NATIVE: test octal"
|
||||||
|
(assert (= 0o1232 666)))
|
||||||
|
|
||||||
|
|
||||||
|
(defn test-binary []
|
||||||
|
"NATIVE: test binary"
|
||||||
|
(assert (= 0b1011101 93)))
|
||||||
|
|
||||||
|
|
||||||
(defn test-fractions []
|
(defn test-fractions []
|
||||||
"NATIVE: test fractions"
|
"NATIVE: test fractions"
|
||||||
(assert (= 1/2 (fraction 1 2))))
|
(assert (= 1/2 (fraction 1 2))))
|
||||||
|
Loading…
Reference in New Issue
Block a user