-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fromNumber :: Number -> Rational? #10
Comments
Here is a (shitty) implementation I'm using. testNumberChar :: Char -> Boolean
testNumberChar char =
let digitArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']
in elem char digitArray
digitsToRational :: String -> Maybe Rational
digitsToRational stringOfDigits =
let
isNumChar = all testNumberChar (toCharArray stringOfDigits)
in case isNumChar of
false -> Nothing
true -> do
let
numeratorStr = replaceAll (Pattern ".") (Replacement "") stringOfDigits
numStrLength = length numeratorStr
index = fromMaybe numStrLength (indexOf (Pattern ".") stringOfDigits)
denominator = 10 `pow` (numStrLength - index)
numerator <- fromString numeratorStr
pure (numerator % denominator) |
And of course some tests: describe "digitsToRational" do
it "converts 137 to 137/1" do
(digitsToRational "137") `shouldEqual` (Just (137 % 1))
it "converts 13 to 13/1" do
(digitsToRational "13") `shouldEqual` (Just (13 % 1))
it "converts 3 to 3/1" do
(digitsToRational "3") `shouldEqual` (Just (3 % 1))
it "converts 0 to 0/1" do
(digitsToRational "0") `shouldEqual` (Just (0 % 1))
it "converts 0.3 to 3/10" do
(digitsToRational "0.3") `shouldEqual` (Just (3 % 10))
it "converts .3 to 3/10" do
(digitsToRational ".3") `shouldEqual` (Just (3 % 10))
it "converts 0.300 to 3/10" do
(digitsToRational "0.300") `shouldEqual` (Just (3 % 10))
it "converts 2.1 to 21/10" do
(digitsToRational "2.1") `shouldEqual` (Just (21 % 10))
it "converts 3.21 to 321/100" do
(digitsToRational "3.21") `shouldEqual` (Just (321 % 100))
it "converts 12.3456 to 123456/10000" do
(digitsToRational "12.3456") `shouldEqual` (Just (123456 % 10000))
it "converts abc to Nothing" do
(digitsToRational "abc") `shouldEqual` Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Might be hard to implement, and would probably have to round sometimes? But it could be useful.
The text was updated successfully, but these errors were encountered: