gpt4 book ai didi

haskell - 功能实例展示

转载 作者:行者123 更新时间:2023-12-03 14:27:33 25 4
gpt4 key购买 nike

我目前正在尝试为原始算术函数编写一个小的 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 吗?如果是,我该如何解决这个问题?

最佳答案

不要使用 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 #-} 打开它

关于haskell - 功能实例展示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com