haskell - Strange pattern matching with functions instancing Show -
so i'm writing program returns procedure given arithmetic problem, wanted instance couple of functions show can print same expression evaluate when test. trouble given code matches (-) first line when should fall second.
{-# options_ghc -xflexibleinstances #-} instance show (t -> t-> t) show (+) = "plus" show (-) = "minus" main = print [(+),(-)]
returns
[plus,plus]
am committing mortal sin printing functions in first place or there way can match properly?
edit:i realise getting following warning:
warning: pattern match(es) overlapped in definition of `show': show - = ...
i still don't know why overlaps, or how stop it.
as sepp2k , mtnviewmark said, can't pattern match on value of identifiers, on constructors and, in cases, implicit equality checks. so, instance binding argument identifier, in process shadowing external definition of (+)
. unfortunately, means you're trying won't , can't ever work.
a typical solution want accomplish define "arithmetic expression" algebraic data type, appropriate show
instance. note can make expression type instance of num
, numeric literals wrapped in "literal" constructor, , operations (+)
returning arguments combined constructor operation. here's quick, incomplete example:
data expression = literal | sum (expression a) (expression a) | product (expression a) (expression a) deriving (eq, ord, show) instance (num a) => num (expression a) x + y = sum x y x * y = product x y frominteger x = literal (frominteger x) evaluate (literal x) = x evaluate (sum x y) = evaluate x + evaluate y evaluate (product x y) = evaluate x * evaluate y integer :: integer integer = (1 + 2) * 3 + 4 expr :: expression integer expr = (1 + 2) * 3 + 4
trying out in ghci:
> integer 13 > evaluate expr 13 > expr sum (product (sum (literal 1) (literal 2)) (literal 3)) (literal 4)
Comments
Post a Comment