haskell - 函数依赖/类型族

标签 haskell types

通过函数依赖,我可以使用多参数类型类来约束类型类中依赖参数的类型。就像这样:

{-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses,TypeSynonymInstances  #-}

class (Num a, Integral b) => F a b | a -> b where
  f :: a -> b

instance F Int Int where
  f = id

instance F Float Integer where
  f = truncate

一切都会完美地进行。

> f (1 :: Int)
1
> f (1.9 :: Float)
1

但是如果我尝试写一些类似的东西

instance F Double String where
  f = show

我会收到以下编译错误:

No instance for (Integral String)
arising from the superclasses of an instance declaration
Possible fix: add an instance declaration for (Integral String)
In the instance declaration for `F Double String'

有没有办法用类型族而不是fundeps来解决这个问题?

最佳答案

基本上不是,这实际上与函数依赖(或类型族)无关。你的类定义有

class (Num a, Integral b) => F a b

它声明 b 必须有一个 Integral 实例。 String 没有 Integral 实例,因此除非您定义,否则您不能拥有 F a String 形式的任何内容

-- String is a type synonym for [Char]
instance Integral [Char] where

我不知道这通常是否明智。如果在系统中为字符串创建 Integral 实例有意义,您可能希望在字符串周围放置一个新类型包装器并为其创建实例。

关于haskell - 函数依赖/类型族,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5624438/

相关文章:

haskell - 使用多参数类型派生扩展

指定类型时 javac "uses unchecked or unsafe operations"

haskell - 如何从元组到自定义数据类型?

reactjs - 如何在react js中检查 Material ui主题的类型? (浅色或深色)

entity-framework - EF 对象与泛型类型的比较

typescript - 继承自错误中断 `instanceof` 检查 TypeScript

parsing - Haskell 函数解析字符串并返回找到的任何 url

haskell - 从树中提取特定类型

haskell - 反转类型族

haskell - 在 haskell 中使用 printf 打印数据库