gpt4 book ai didi

haskell - 如何将类型构造函数限制为返回 Ord 类型?

转载 作者:行者123 更新时间:2023-12-04 13:52:04 24 4
gpt4 key购买 nike

假设我有一个树的实现:

data Tree a children = EmptyTree | Tree a (children (Tree a children))

是否可以限制 children返回 Ord类型?

类似于:
data (Ord children *) => Tree a children = EmptyTree | Tree a (children (Tree a children))

最佳答案

我至少可以想到两种方法:

1. GADT

例如见here .

{-# LANGUAGE GADTs #-}

data Tree a children where
Empty :: Tree a children
Tree :: Ord (children a) => a -> children (Tree a children) -> Tree a children

现在你可以这样做:
ghci> let t = Tree 1 [Tree 2 [], Empty]
ghci> :t t
t :: Tree Integer []

2. 智能构造函数

您可以将常规数据类型与具有受限类型签名的智能构造函数一起使用:
{-# LANGUAGE FlexibleContexts #-}

data Tree a children = Empty | Tree a (children (Tree a children))

empty :: Tree a children
empty = Empty

tree :: Ord (children a) => a -> children (Tree a children) -> Tree a children
tree val rest = Tree val rest

你现在可以这样做:
ghci> let t = tree 1 [tree 2 [], empty]
ghci> :t t
t :: Tree Integer []

但如果您尝试添加不可订购的类型:
ghci> let t = tree (+1) []
<interactive>:69:9:
No instance for (Ord (a0 -> a0))
arising from a use of `tree'
Possible fix: add an instance declaration for (Ord (a0 -> a0))
In the expression: tree (+ 1) []
In an equation for `t': t = tree (+ 1) []

关于haskell - 如何将类型构造函数限制为返回 Ord 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14735463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com