parse and evaluate math expressions
Go to file
2022-07-14 18:00:30 +01:00
src/Numeric Corrected an issue in replaceVariable that was not adding padding in tokenized expression 2022-07-14 18:00:30 +01:00
.gitignore initial commit 2016-11-03 01:42:22 +03:30
.travis.yml chore: remove stack 7.8.4 osx 2016-11-04 18:20:25 +03:30
LICENSE initial commit 2016-11-03 01:42:22 +03:30
mathexpr.cabal fix: move from Data.MathExpr to Numeric.MathExpr 2016-11-04 22:35:04 +03:30
README.md add travis badge 2016-11-04 16:40:38 +03:30
Setup.hs initial commit 2016-11-03 01:42:22 +03:30
stack.yaml initial commit 2016-11-03 01:42:22 +03:30

mathexpr Travis

Ever wanted to take as input a mathematical expression to fill in values and use it? mathexpr is exactly what you need.

I also wrote this in JavaScript some time ago: Equation

Examples

Simple evaluation of expressions:

import Data.MathExpr

main = do
  expr <- getLine -- a mathematical expression, e.g. sin x + y ^ 2
  -- replace x and y with the specified values and evaluate: sin 2 + 5 ^ 2 = 25.909..
  print $ evaluate def expr [("x", 2), ("y", 5)]

Using custom operators and functions:

import Data.MathExpr


-- operators are in the form (character, precedence, function)
-- example: ('+', 0, (+)), ('*', 1, (*))
-- the function should have the type (Double -> Double -> Double)
-- the higher the precedence, the sooner the operator operates

-- functions are in the form (name, function)
-- example: ("ln", log)
-- the function should have the type (Double -> Double)

main =
  let avg a b = (a + b) / 2
  let settings = Settings { operators = defaultOperators ++ [('~', 0, avg)]
                          , functions = defaultFunctions ++ [("trunc", fromIntegral . truncate)]
  evaluate settings "3 ~ 5" [] -- 4
  evaluate settings "trunc 1.1" [] -- 1