实例显示功能

时间:2012-05-11 12:18:58

标签: haskell

我正在尝试为原始算术函数编写一个小的Show实例。

目标是制作一个可展示的功能列表。

show的非常简单的功能如下:

  showOp :: (Int -> Int -> Int) -> String
  showOp op
    | op 3 3 == 6 = "plus"
    | op 3 3 == 0 = "minus"
    | op 3 3 == 9 = "times"
    | op 3 3 == 1 = "divide"
    | otherwise = "undefined"

但是我无法获得Show for(Int - > Int - > Int)的实例。我这样试过:

    instance Show (Int -> Int -> Int) where
    show op = show "asdf"

但它不起作用。 WinHugs只返回错误

    Syntax error in instance head (variable expected)

甚至可以定义Show for functions?如果是的话,我该如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

不要使用WinHugs。使用GHC。

事实上,在最近的Haskell平台版本中,已经有Show的一个函数实例。

Prelude Text.Show.Functions> show (+1)
"<function>"
Prelude Text.Show.Functions> show (\x -> x ++ "foo")
"<function>"

现在,在您的情况下,您需要-XFlexibleInstances,因为您的实例不是(Constructor a1 .. an)形式,其中a1 .. an是不同的类型变量。

使用{-# LANGUAGE FlexibleInstances #-}

启用它

答案 1 :(得分:3)

(这不是一个答案(唐的涵盖),但是评论的时间太长了)

代码有很多重复的逻辑(特别是op 3 3 ==会发生很多),但是要做得更清洁:case expressions。这允许我们计算op 3 3一次,然后处理各种情况(与函数定义中的模式匹配完全相同)。

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

答案 2 :(得分:1)

您也可以使用Hugs。

使用hugs -98 +orunhugs -X-98 +o启动拥抱,并在源文件中使用{-# LANGUAGE FlexibleInstances #-}