haskell - 在 Haskell 中使用中间多态类型组合函数

标签 haskell polymorphism function-composition

我有以下文件:

module SimpleComposition where

class Intermediate a where
    f :: a -> Int
    g :: Char -> a

h :: Char -> Int
h = f . g

当尝试在 ghci 中加载它时,出现错误:

main.hs:8:5: error:
    * No instance for (Intermediate a0) arising from a use of `f'
    * In the first argument of `(.)', namely `f'
      In the expression: f . g
      In an equation for `h': h = f . g
  |
8 | h = f . g
  |     ^

我认为问题是有人可能在这个组合中使用了 2 种不同的类型,它们是 Intermediate 的实例。我如何保证我导出这个模块时是一样的?

PS:与我之前提出的问题 (How to compose polymorphic functions in Haskell?) 相比,这是我遇到的问题的一个更好的最小示例。

最佳答案

问题不在于无法推断出实例,而是编译器真的无法知道您可能需要什么类型。 g 可以产生任何类型的请求(假设它有一个 Intermediate 实例),f 可以使用任何这样的类型......但是没有人指定哪个

但这很容易解决:现在只需选择一种类型。当然,它需要是一个确实有实例的;例如如果你有

instance Intermediate Char where
  f = fromEnum
  g = id

然后你就可以使用了

h :: Char -> Int
h = (f :: Char -> Int) . g

修复类型选择的更简洁的方法是使用句法扩展:

{-# LANGUAGE TypeApplications #-}

h = f @Char . g

...或者,为了强调您只是在中间固定类型,

h = f . id @Char . g

关于haskell - 在 Haskell 中使用中间多态类型组合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65374433/

相关文章:

haskell - 这个列表理解代码有什么问题?

python - 根据传递给构造函数的参数实现Python类

c++ - 专业面试的意外答案

performance - Haskell:不同功能组成的性能差异?

haskell - 递归函数组合中的惰性

python - Haskell、Python 和 Ruby 中的列表理解

Haskell - 函数式编程技巧(练习 4.3)

haskell - 我的计时器总是返回 0

json - 奇怪的 JSON 解释(多态类型),如何解决?

clojure - 在 Clojure 中将单参数函数合并为多参数函数