haskell - 如何从子函数内的函数引用类型

标签 haskell types where-clause

是否可以从函数的子函数之一的定义中引用类型? (有关更多详细信息,请参阅下面代码中的注释)

module TypesAndSubFunctions where

class DingBat k where

foo :: DingBat k => k -> String
foo kv = "foo"
  where
    -- how can I define bar so that the type 'k2' is the same 
    -- as k from foo? Or is this not possible?
    --
    -- The following causes an error, because k2 isn't the same type
    -- as foo's k. But I can't seem to find a way to reference foo's k
    -- without specifying it as an arg (as I do in bar2). Is this just
    -- the way haskell is?
    --
    -- I would think there should be a simple way to reference k from
    -- foo with the type definition of bar, but I can't see how.
    -- bar :: DingBat k2 => k2 -> String
    -- bar kv2 = ding2 kv kv2

    -- To restate the problem, I would like the same functionality for
    -- bar as bar2, below, but without having to specify the first arg
    bar2 :: DingBat k => k -> k -> String
    bar2 kv kv2 = ding2 kv kv2

ding2 :: DingBat k => k -> k -> String
ding2 = undefined

最佳答案

这应该可以完成工作。要重用 k,您需要打开一个非常常见的扩展。

{-# LANGUAGE ScopedTypeVariables #-}

foo :: forall k . DingBat k => k -> String
foo kv = "foo"
  where
  bar :: k -> String
  bar kv2 = ding2 kv kv2

关于haskell - 如何从子函数内的函数引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51375989/

相关文章:

haskell - 类型级列表的多态构造函数

generics - 为什么 Scala 无法推断出本例中的类型参数?

sql - 使用 WHERE、AND 和 ILIKE 查询

typescript - 是否可以为方法装饰器选项提供类型安全

c++ - `int` 在 C++ 中默认是 `signed long int` 吗?

mysql - JOIN、GROUP BY、SUM 问题 Mysql

sql - 如何设置存储过程参数可以或不可以由用户传递值?

haskell - Parsec 不解析换行符

haskell - 使用 Sublime 2 进行 Haskell 开发?

haskell - 什么是类型孔勘探开发方式?