我一直在尝试使用指定 eval 函数的 Component 类型类在 Purescript 中开发组件系统。eval 函数可以由组件的每个子组件递归调用,实质上是获取输入的值。
由于组件可能希望使用运行时值,因此还向 eval 传递了一条记录。我的目标是要求顶级 eval 的 Record 参数中的行包含每个子组件的所有行。对于本身不使用任何行的组件来说,这并不是太困难,但它们的单个子组件确实如此,因为我们可以简单地将子组件行传递给组件。这显示在evalIncrement.
import Prelude ((+), one)
import Data.Symbol (class IsSymbol, SProxy(..))
import Record (get)
import Prim.Row (class Cons, class Union)
class Component a b c | a -> b where
eval :: a -> Record c -> b
data Const a = Const a
instance evalConst :: Component (Const a) a r where
eval (Const v) r = v
data Var (a::Symbol) (b::Type) = Var …Run Code Online (Sandbox Code Playgroud) 假设我有一个由多个多态变体(协变)组成的类型,如下所示:
[> `Ok of int | `Error of string]
Run Code Online (Sandbox Code Playgroud)
让我们进一步假设我想将此定义分解为某种类型构造函数和一个具体类型int。我的第一次尝试如下:
type 'a error = [> `Ok of 'a | `Error of string]
Run Code Online (Sandbox Code Playgroud)
然而,使用这样的定义会产生一个非常奇怪的类型错误,提到一个'b没有出现在定义中任何地方的类型变量。
$ ocaml
OCaml version 4.07.0
# type 'a error = [> `Ok of 'a | `Error of string ];;
Error: A type variable is unbound in this type declaration.
In type [> `Error of string | `Ok of 'a ] as 'b the variable 'b is unbound
Run Code Online (Sandbox Code Playgroud)
这'b是一个自动生成的名称,添加一个显式'b将变量转换为'c …
ocaml parametric-polymorphism polymorphic-variants row-polymorphism
如果这是一个愚蠢的问题,请耐心等待.如何键入一个带有两个记录并返回其公共字段数组的泛型函数?
比方说我有:
type A = { name :: String, color :: String }
type B = { name :: String, address :: Address, color :: String }
myImaginaryFunction :: ???
-- should return ["name", "color"] :: Array of [name color]
Run Code Online (Sandbox Code Playgroud)
我想编写一个函数,它接受任何两种类型的记录并返回一个公共字段数组.一个haskell解决方案也可以工作.