Reputation: 541
Is there any way I can make a function that takes a mathematical equation as an argument? For example
derive :: --equation
...
main = print (derive $ x**2-x)
Would I need to make a custom data type?
Upvotes: 0
Views: 166
Reputation: 531625
Yes; you need to create a data type that represents a formula, rather than passing a Haskell expression that needs to be evaluated. For example,
data Formula = Term Int Int -- coefficient and exponent
| Sum Formula Formula deriving Show
derive :: Formula -> Formula
derive (Term coeff exp) = Term (coeff * exp) (exp - 1)
derive (Sum x y) = Sum (derive x) (derive y)
main = print (derive $ Sum (Term 1 2) (Term (-1) 1))
Upvotes: 3