I have this type that I made an instance of Num:
data MyNumType = MyNumType [String] String deriving Show
myNumType n = MyNumType [n] n --constructor
instance Num MyNumType where
(+) (MyNumType a b) (MyNumType c d) = MyNumType (a ++ c) ("(" ++ b ++ "+" ++ d ++ ")")
(-) (MyNumType a b) (MyNumType c d) = MyNumType (a ++ c) ("(" ++ b ++ "-" ++ d ++ ")")
(*) (MyNumType a b) (MyNumType c d) = MyNumType (a ++ c) ("(" ++ b ++ "*" ++ d ++ ")")
fromInteger n = MyNumType [show n] (show n)
abs (MyNumType a b) = MyNumType a ("abs(" ++ b ++ ")")
signum (MyNumType a b) = MyNumType a ("signum(" ++ b ++ ")")
The purpose of this MyNumType is to keep track of the calculations that variables undergo, here is an example:
a = myNumType "a"
b = myNumType "b"
myComputation = a + b
-- myComputation --> MyNumType ["a","b"] "(a+b)"
myComputation keeps track of independent variables and functions that have been computed from them. I would like to create a haskell function from “(a+b)”: \a b -> a+b
I understand that using strings is not the most efficient way to do this. In julia I would have used some symbolic computation library or built functions from the strings with metaprogramming.
So if you have better ways to do it every answer is welcome.