Haskell:为String和/或[String]的异构列表键入(没有样板)?

时间:2015-05-13 13:21:46

标签: list haskell types existential-type heterogeneous

我希望有一个$( "#length" ).change(function() { var numPerPage = $("#length").val()); }); 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"]]

有人知道这是否可行?

1 个答案:

答案 0 :(得分: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

虽然没有fLfS别名,但我只是这样做,所以我不必输入那么多。它只是感觉没有样板,因为编译器会为你放置那些函数调用,但你仍然会有将这些值转换为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]]

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