D
D
Daniil Kolesnichenko2015-05-17 15:03:57
Haskell
Daniil Kolesnichenko, 2015-05-17 15:03:57

How to check if a string is a number in Haskell?

There is this code in Haskell:

import Data.Char

isAtom :: String -> Bool
isAtom word = all isAlpha word

token :: String -> String
token word 
    | word `elem` ["+", "-", "/", "*", "%"] = "operator"
    | word == "(" = "lbracket"
    | word == ")" = "rbracket"
    | (c1 == '"') && (c2 == '"') = "string"
    | isAtom word = "atom"
    where
        c1 = head word
        c2 = last word

In general, it should be an interpreter for Lisp-like arithmetic expressions. Actually, I learned to recognize all types of lexemes, except for numbers. While two options come to mind, I don't like both: either try to apply read word :: Floatand catch an exception, or loop through all the characters in the string and check if they are digits. The second option would be good if it weren't for fractional numbers - you could just write all isDigit word. Is there any simpler and more obvious way to do this?
PS At the output, the program must interpret expressions of the form (+ 1 (* 5 4 (/ 4 2)) 3). I already wrote this in Python, now I'm just rewriting the same in Haskell to get my hands on it a little before writing a full-fledged interpreter for "Write your Scheme in 48 hours"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ruchkin, 2015-05-17
@KolesnichenkoDS

Use readMaybefromText.Read

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question