实例显示功能

sch*_*gel 5 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"
Run Code Online (Sandbox Code Playgroud)

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

    instance Show (Int -> Int -> Int) where
    show op = show "asdf"
Run Code Online (Sandbox Code Playgroud)

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

    Syntax error in instance head (variable expected)
Run Code Online (Sandbox Code Playgroud)

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

Don*_*art 6

不要使用WinHugs.使用GHC.

实际上,在最近的Haskell Platform版本中,已经有Show的一个函数实例.

Prelude Text.Show.Functions> show (+1)
"<function>"
Prelude Text.Show.Functions> show (\x -> x ++ "foo")
"<function>"
Run Code Online (Sandbox Code Playgroud)

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

打开它 {-# LANGUAGE FlexibleInstances #-}