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

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

问题描述

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



目标是让功能列表显示。



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

  showOp ::(Int  - > Int  - > Int) - >字符串
showOp op
| op 3 3 == 6 =plus
| op 3 3 == 0 =minus
| op 3 3 == 9 =times
| op 3 3 == 1 =divide
|否则=未定义

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

  instance Show(Int  - > Int  - > Int)其中
show op = showasdf

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

pre $ 实例头中的语法错误(预期的变量)

甚至有可能为函数定义Show?如果是这样,我该如何解决这个问题? 解决方案

不要使用WinHugs。使用GHC。实际上,在最近的Haskell平台版本中,已经有一个用于Show的函数实例。

  Prelude Text.Show.Functions>显示(+1)
<函数>
前奏Text.Show.Functions> show(\ x - > x ++foo)
< function>

现在,就您而言,您需要 -XFlexibleInstances on,因为您的实例不是(构造函数a1 .. an)形式,其中a1 .. an是不同类型的变量。



使用 { - #LANGUAGE FlexibleInstances# - }

打开它

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

Goal ist to make a list of functions showable.

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"

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"

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

    Syntax error in instance head (variable expected)

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

解决方案

Don't use WinHugs. Use GHC.

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>"

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.

Turn it on with {-# LANGUAGE FlexibleInstances #-}

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

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