功能实例展示 [英] Instance Show for function

查看:25
本文介绍了功能实例展示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently trying to write a little Show instance for primitive arithmetic functions.

目标是制作可显示的功能列表.

Goal ist to make a list of functions showable.

非常简单的 show 函数如下所示:

The very simple function for show looks like that:

  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) 的实例.我是这样试的:

But I can't get an instance of Show for (Int -> Int -> Int). I tried it like that:

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

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

But it doesn't work. WinHugs just returns the Error

    Syntax error in instance head (variable expected)

甚至可以为函数定义 Show 吗?如果是,我该如何解决这个问题?

Is it even possible to define Show for functions? If it is, how could I tackle that problem?

推荐答案

不要使用 WinHugs.使用 GHC.

Don't use WinHugs. Use GHC.

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

In fact, in recent Haskell Platform versions there is already an instance of functions for Show.

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

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

Now, in your case, however, you need -XFlexibleInstances on, since your instance isn't of the form (Constructor a1 .. an) where a1 .. an are distinct type variables.

使用 {-# LANGUAGE FlexibleInstances #-}

这篇关于功能实例展示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆