将基本算术函数显示为字符串

时间:2013-05-03 09:02:14

标签: haskell

对于家庭作业,子任务是使算术函数(+)(-)(*)div可以显示。

我们解决了剩下的任务,但我们被困在这里。现在我们正在使用the solution to this question here来区分操作:

showOp op = case op 3 3 of
          6 -> "plus"
          0 -> "minus"
          9 -> "times"
          1 -> "divide"
          _ -> "undefined"

然而,这让我觉得像showOp (\a b -> a * 3 - y)收益"plus"这样丑陋。

有没有办法更好地区分运营商?

我们正在使用winhugs atm和相应的开关-98 +o,以便能够使用所需的扩展程序。

修改 根据要求,实际的分配与数组(特别是Array Int (Int -> Int -> Int))有关。它与生成满足某些条件的运算符数组有关。

作业说明:

  

使数据类型Array Int (Int->Int-Int)成为Show的实例。以前练习中的算术运算应表示为“加”,“减”,“次”和“div”。

提前获得任何帮助

1 个答案:

答案 0 :(得分:2)

使用归纳法:)

{-# LANGUAGE FlexibleInstances #-}

instance Eq (Int-> Int -> Int) where 
  f == g = induce f g where
    base = 1
    n = 2
    induce f g = and [f 1 n' == g 1 n' | n' <- [base, n, n+1]]

instance Show (Int-> Int -> Int) where 
  show a = showOp a where
    showOp op = case lookup op ops of
                  Just a -> a
                  otherwise  -> "undefined"
    ops = [((+),"plus")
          ,((-),"minus")
          ,((*),"times")
          ,(div,"divide")]

输出:

*Main> (\a b -> a * 3 - b) :: (Int->Int->Int)
undefined