[英]Haskell Type Classes in Type Alias declaration
I am trying to develop a module that performs different algorithms over a set of states by receiving the functions to manage them as paremeters. 我正在尝试开发一个模块,该模块通过接收将其作为参数进行管理的功能来对一组状态执行不同的算法。 I was defining different type aliases to make it easier to implement; 我正在定义不同的类型别名,以使其易于实现。 a simple example to understand this would be: 一个简单的例子可以理解为:
-- Function that expands a state
type Expand = State -> State
-- Function that evaluates a state
type Eval = State -> Float
-- Group of states
type Tree = [State]
And then I realized that I wanted State
to be the alias of a type that is equatable: I really don't care if the user's states are (Int, Int)
, Float
, or String
as long as it's possible for him to implement the Expand
and Eval
functions and for me to compare two different states. 然后我意识到我想让State
作为可等于类型的别名:我真的不在乎用户的状态是(Int, Int)
, Float
还是String
,只要他有可能实现Expand
和Eval
函数,对我来说,比较两个不同的状态。
How can I generalize the type State
to achieve this? 我如何概括State
类型来实现这一目标? The intuitive thing that comes to my mind is something like type State = (Eq a) => a
but that is obviously not possible without an a
in scope. 我想到的直觉是类似type State = (Eq a) => a
但是如果没有a
范围,这显然是不可能的。 Is there an easy way for me to declare functions that treat State
as a black box? 我有一种简单的方法可以声明将State
视为黑匣子的函数吗?
You need to include the generic state as a type parameter. 您需要将通用状态作为类型参数包括在内。
type Expand s = s -> s
type Eval s = s -> Float
type Tree s = [s]
It's impossible to completely hide it, because eg Expand
for an (Int, Int)
state is a completely different type than for a String
state. 完全隐藏它是不可能的,因为例如(Int, Int)
状态的Expand
是与String
状态完全不同的类型。
As for the Eq
constraint. 至于Eq
约束。 Typically, you would include that locally only in the specific function that requires the constraint. 通常,只在本地将其包含在需要约束的特定函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.