小编bim*_*mmo的帖子

Haskell:可以在函数定义中使用类型变量吗?

我有一个与Haskell类型系统有关的问题.这不是我第一次遇到类型系统的限制.我将省略我的项目详细信息并使用简化示例.这是一些代码:

-- Works
foo :: (Bounded a, Enum a) => a
foo = minBound

-- "ambiguous" constraint:
-- 'a' has no occurrences in type declaration
bar :: (Bounded a, Enum a) => Int
bar = fromEnum minBound

-- Too much information in return
-- but I can show haskell the appropriate type of 'min'
baz :: (Bounded a, Enum a) => (a, Int)
baz = let min = minBound
    in (min, someFunction . fromEnum $ min)

-- Type constraint 'a' …
Run Code Online (Sandbox Code Playgroud)

haskell types

13
推荐指数
1
解决办法
491
查看次数

如何定义超类?

如何在Haskell中定义超类?我的情况是我已经定义了一个类StringHashed,它将成员的名称映射为String.我希望实现,连接质量,所有tShow t通过将字符串名称简单地返回show t.我是否正确地说StringHashed现在是Show的超类?以下是我想写的内容:

class StringHashed t where
    stringHash :: t -> String

instance Show t => StringHashed t where
    stringHash = show
Run Code Online (Sandbox Code Playgroud)

但是Haskell抱怨无效的实例声明.我也尝试过instance StringHashed (Show t)其他语法运球; 没有人对我有用.我还阅读了关于GHC wiki的提议,但没有提供任何解决方案.这是一个.我担心使用-XFlexibleInstances只是因为它不是默认的.有没有一种正确的方法来实现一般的实例声明?或者我对Haskell的类型系统要求太高了?

haskell class instance

4
推荐指数
1
解决办法
263
查看次数

使用">",Haskell没有(Ord int)的实例

其他问题和问题虽然相似,但并不像这个.在这个特定的编译器错误中,Haskell GHC将不会编译以下代码,原因如下.我根本不明白 - 代码很简单.

--factorial

fact :: int -> int
fact 0 = 1
fact n | n > 0 = n * fact(n - 1)

main = print (fact 10)
Run Code Online (Sandbox Code Playgroud)

(错误:)

No instance for (Ord int) arising from a use of `>'
Possible fix:
add (Ord int) to the context of
the type signature for fact :: int -> int
In the expression: n > 0
In a stmt of a pattern guard for
an equation for `fact':
n …
Run Code Online (Sandbox Code Playgroud)

haskell compilation

3
推荐指数
1
解决办法
2415
查看次数

为什么Haskell会在我的类型上输入一个文字?

我为Rational编写了一个包装类型,NaN是一个除零而不是崩溃的程序.代码编译时没有错误或警告.这是(希望,所有)相关代码:

data SafeRational =
    SRatio Rational |
    SRatioNaN

instance Show (SafeRational) where
    show (SRatio x) = show . fromRational $ x
    show SRatioNaN  = "NaN"

instance Num (SafeRational) where
    (+) (SRatio a) (SRatio b)   = SRatio (a+b)
    (+) _ _                     = SRatioNaN -- Good?
    (*) (SRatio a) (SRatio b)   = SRatio (a*b)
    (*) _ _                     = SRatioNaN
    signum (SRatio a)           = SRatio (signum a)
    signum SRatioNaN                = SRatio 0
    abs (SRatio a)              = SRatio (abs a)
    abs SRatioNaN               = SRatioNaN …
Run Code Online (Sandbox Code Playgroud)

haskell casting

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

标签 统计

haskell ×4

casting ×1

class ×1

compilation ×1

instance ×1

types ×1