2

我想要一个和的异构列表String[String]例如:

strs = ["h", ["x", "y"], "i", ["m", "n", "p"]]

我知道我可以使用自定义数据类型来做到这一点:

data EitherOr t = StringS t | StringL [t]

eitherOrstrs :: [EitherOr String]
eitherOrstrs = [StringS "h", StringL ["x", "y"], StringS "i", StringL ["m", "n", "p"]]

但我很好奇这是否可能在没有任何样板的情况下,如上strs所示。

到目前为止,我已经尝试过:

{-# LANGUAGE ExistentialQuantification #-}

class Listable a where
  toListForm :: [String]

instance Listable String where
  toListForm s = [s]

instance Listable [String] where
  toListForm = id

strs :: forall a. Listable a => [a]
strs = ["h", ["x", "y"], "i", ["m", "n", "p"]]

但还没有找到工作方法:

The class method ‘toListForm’
mentions none of the type or kind variables of the class ‘Listable a’
When checking the class method: toListForm :: [String]
In the class declaration for ‘Listable’

有谁知道这是否可能?

4

1 回答 1

7

这将适用于具有一些扩展技巧的任意嵌套字符串列表:

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}

import GHC.Exts
import Data.String

data MyStringListThingy
    = String String
    | List [MyStringListThingy]
    deriving (Eq, Show)

instance IsString MyStringListThingy where
    fromString = String

instance IsList MyStringListThingy where
    type Item MyStringListThingy = MyStringListThingy
    fromList = List
    fromListN _ = List
    toList (String s) = [String s]
    toList (List ss) = ss

strs :: MyStringListThingy
strs = ["h", ["x", "y"], "i", ["m", "n", "p", ["q", ["r", "s"]]]]

不过,您至少需要 GHC 7.8,可能是 7.10(我没有用 7.8 测试过)。

如果没有样板,这并不能完全摆脱,编译器会将隐式函数调用放在每个文字前面:

strs = fL [fS "h", fL [fS "x", fS "y"], fS "i", fL [fS "m", fS "n", fS "p", fL [fS "q", fL [fS "r", fS "s"]]]]
    where
        fL = fromList
        fS = fromString

尽管没有fLandfS别名,我只是这样做了,所以我不必输入太多。它只是感觉没有样板,因为编译器将这些函数调用放在那里,但您仍然需要将这些值转换为MyStringListThingy.

您可能也可以使用这个技巧摆脱异构数字列表,因为数字文字也是多态的,这也是OverloadedStringsOverloadedLists扩展对这些文字所做的。通过创建一个包含列表和字符串的类型,然后实例化必要的类型类,您允许 Haskell 将这些文字转换为您的自定义类型。TypeFamilies扩展IsList仅对实例是必需的。如果您想在 GHCi 中使用它,您还必须在其中启用所有这些扩展,但它绝对有效。

一个更通用的实现是

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}

import GHC.Exts
import Data.String

data NestedList a
    = Item a
    | List [NestedList a]
    deriving (Eq, Show)

instance IsList (NestedList a) where
    type Item (NestedList a) = NestedList a
    fromList = List
    fromListN _ = List
    toList (List xs) = xs
    toList item = [item]

instance IsString (NestedList String) where
    fromString = Item

instance Num a => Num (NestedList a) where
    fromInteger = Item . fromInteger

Num实例并没有实现它需要的所有东西,仅仅足以证明它是有效的

> [1, [2, 3]] :: NestedList Int
List [Item 1, List [Item 2, Item 3]]

不过,我不建议在实际代码中使用它。

于 2015-05-13T13:37:04.100 回答