小编Har*_*iss的帖子

如何为单一类型专门化(重载)函数的行为?

我正在使用 Real World Haskell,并且作为练习的一部分,我意识到我想要一个类似于 的函数show :: Show(a) => a -> String,但它不影响字符串(而不是转义引号)。在伪代码中,我想要的是:

show' :: String -> String
show' = id

show':: Show(a) => a -> String
show' = show
Run Code Online (Sandbox Code Playgroud)

显然这不起作用(ghc 抱怨多个类型签名和多个声明)。看来我应该改用类型类。当我尝试编写此代码时,编译器不断建议我添加更多语言扩展:

{-# LANGUAGE FlexibleInstances, UndecidableInstances, IncoherentInstances #-}

class Show' a where
  show' :: a -> String

instance Show' String where
  show' = id

instance (Show a) => Show' a where
  show' = show

-- x == "abc"
x = show' "abc"
y = show' 9
Run Code Online (Sandbox Code Playgroud)

起初,这似乎工作:x == "abc" …

polymorphism haskell typeclass

0
推荐指数
1
解决办法
79
查看次数

标签 统计

haskell ×1

polymorphism ×1

typeclass ×1