KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I was challenging myself to write a simple version of the calculator discussed to here , and came up with a way to retrieve operators by looking up a string: ops = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))] This worked fine. However, when I tried to add either ("^", (^)), ("mod", (mod)) or ("div", (div)) to the list, I was greeted with: Ambiguous type variable `a0' in the constraints: (Fractional a0) arising from a use of `/' at new2.hs:1:50-52 (Integral a0) arising from a use of `mod' at new2.hs:1:65-67 (Num a0) arising from a use of `+' at new2.hs:1:14-16 Possible cause: the monomorphism restriction... Alternatively, grouping the six operators without (/) worked fine as well, but gave me all sorts of errors when I tried to create one function that could return any of the seven operators (by using if-else, or looking up in two different lists, for example). Returning any of the six was fine, or working only with (+), (-), (*) and (/) worked fine too, using the simple function: findOp op = fromJust $ lookup op ops What could be a convenient way to store and retrieve any of these seven operators based on a string or something else? Or perhaps I should be thinking of another way to calculate the parsed input-string of the calculator? (I think eval and parsec were excluded from this excercise, and I would prefer not to use -XNoMonomorphismRestriction, if that were an option) Here's my elementary calculator that can parse +, -, *, and / with correct precedence, and which I was hoping to continue and toy with: import Data.Maybe ops = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))] parseLex a = fst $ head a findOp op = fromJust $ lookup op ops calculate str accum op memory multiplication | operand1 /= "" &&
Tags (comma-separated)
Save Edits
Cancel