有没有办法在Haskell中做更多“动态”数据构造函数?

时间:2010-02-12 16:08:35

标签: data-structures haskell constructor

是否有一些Haskell扩展能够创建比GADT更复杂的数据构造函数?

假设我想创建一个有序列表的数据结构,并且有一个类似于(:)的数据构造函数,它与列表一起使用,具有类型签名:

data MyOrdList a where
    (>>>) :: (Ord a) -> a -> MyOrdList a -> MyOrdList a

但我希望(>>>)有一个特定的行为,如下所示:

(>>>) :: (Ord a) => a -> [a] -> [a]
x >>> [] = [x] 
x >>> xs = low ++ [x] ++ high 
  where low  = filter (<x) xs
      high = filter (>x) xs

因此结构将始终是有序结构。 (我现在不知道这是一个好习惯,我只是提供了我想要的行为类型的最简单的例子)。

当然我可以使用函数(>>>),但是我将没有模式匹配和其他好处我>>>是一个数据构造函数。

有没有办法做这样的事情?

2 个答案:

答案 0 :(得分:6)

您可以使MyOrdList成为抽象类型,(>>>)成为函数并使用视图模式。为简单起见,我在这里使用标准列表作为“后端”。

module MyOrdList
  (MyOrdList,
   MyOrdListView (OrdNil, OrdCons),
   (>>>),
   emptyOrdList,
   ordview
  ) where

import Data.List (sort)

newtype MyOrdList a = List [a]
  deriving Show

data MyOrdListView a = OrdNil | OrdCons a (MyOrdList a)

infixr 5 >>>

(>>>) :: (Ord a) => a -> MyOrdList a -> MyOrdList a
x >>> (List xs) = List (sort $ x:xs)

emptyOrdList = List []

ordview :: MyOrdList a -> MyOrdListView a
ordview (List []) = OrdNil
ordview (List (x:xs)) = OrdCons x (List xs)

你可以这样使用它:

{-# LANGUAGE ViewPatterns #-}

import MyOrdList

ordlength :: MyOrdList a -> Int
ordlength (ordview -> OrdNil) = 0
ordlength (ordview -> OrdCons x xs) = 1 + ordlength xs

使用:

*Main> ordlength $ 2 >>> 3 >>> 1 >>> emptyOrdList 
3
*Main> 2 >>> 3 >>> 1 >>> emptyOrdList 
List [1,2,3]

所以你的类型是抽象的,列表只能由emptyOrdList(>>>)构建,但你仍然有一些模式匹配方便。

答案 1 :(得分:3)

您可以使:>>>成为数据构造函数,但您必须隐藏它以保留不变量。请注意,您可以像render中那样对其进行模式匹配:

module MyOrdList (mkMyOrdList,MyOrdList,render) where

import Data.List

import qualified Data.ByteString as BS

data MyOrdList a
  = EmptyDataList
  | (:>>>) a (MyOrdList a)
  deriving (Show)

mkMyOrdList [] = EmptyDataList
mkMyOrdList xs = y :>>> mkMyOrdList ys
  where y = minimum xs
        ys = delete y xs 

render :: (Show a) => MyOrdList a -> String
render EmptyDataList = "<empty>"
render (x :>>> xs) = (show x) ++ " -> " ++ render xs

然后您可以使用

中的MyOrdList模块
module Main where

import Control.Applicative
import System.IO

import qualified Data.ByteString as BS

import MyOrdList

main = do
  h <- openBinaryFile "/dev/urandom" ReadMode 
  cs <- readBytes 10 h
  -- but you cannot write...
  -- let bad = 3 :>>> 2 :>>> 1 :>>> EmptyOrdList
  putStrLn (render $ mkMyOrdList cs)
  where
    readBytes 0 _ = return []
    readBytes n h = do c <- BS.head <$> BS.hGet h 1 
                       cs <- readBytes (n-1) h
                       return (c:cs)

示例输出:

54 -> 57 -> 64 -> 98 -> 131 -> 146 -> 147 -> 148 -> 190 -> 250 -> <empty>