14

假设我已经用 Haskell 类型对自然数进行了编码,并且我有一种方法可以对它们进行加减运算:

data Zero
data Succ n
-- ...

我已经看到了各种创建可变参数函数外观的代码,例如this,它允许以下内容:

buildList "polyvariadic" "function" "wut?" :: [String]
-- ["polyvariadic","function","wut?"]

我想知道的是我是否可以在此基础上构建一个只接受与类型号实例相对应的参数数量的函数。我想要做的看起来像:

one = Succ Zero
two = Succ one
three = Succ two

threeStrings :: String -> String -> String -> [String]
threeStrings = buildList three

threeStrings "asdf" "asdf" "asdf"
-- => ["asdf","asdf","asdf"]

threeStrings "asdf"
-- type checker is all HOLY CHRIST TYPE ERROR

threeStrings "asdf" "asdf" "asdf" "asdf"
-- type checker is all SWEET JESUS WHAT YOU ARE DOING

我知道这很愚蠢,可能是在浪费我的时间,但这似乎是周末有趣的事情。

4

4 回答 4

18

好的。是的。当然,通过围绕递归实例线程化数字类型。

首先,一些样板:

{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses  #-}
{-# LANGUAGE EmptyDataDecls         #-}
{-# LANGUAGE FlexibleInstances      #-}
{-# LANGUAGE FlexibleContexts       #-}
{-# LANGUAGE ScopedTypeVariables    #-}

你的习惯:

data Zero
data Succ n

可变参数函数的递归构建器,现在带有n参数:

class BuildList n a r | r -> a where
    build' :: n -> [a] -> a -> r

一个基本情况:当我们到达时停止Zero

instance BuildList Zero a [a] where
    build' _ l x = reverse $ x:l

否则,减一并递归:

instance BuildList n a r => BuildList (Succ n) a (a->r) where
    build' (_ :: Succ n) l x y = build' (undefined :: n) (x:l) y

现在,我们只想循环 3 次,所以写下来:

build :: BuildList (Succ (Succ Zero)) a r => a -> r
build x = build' (undefined :: Succ (Succ Zero)) [] x

完毕。

测试:

> build "one" "two" "three" :: [[Char]]
["one","two","three"]

任何更少或更多都是错误:

*Main> build "one" "two" "three" "four" :: [[Char]]

<interactive>:1:1:
    No instance for (BuildList Zero [Char] ([Char] -> [[Char]]))

*Main> build "one" "two" :: [[Char]]

<interactive>:1:1:
    No instance for (BuildList (Succ Zero) [Char] [[Char]])
于 2011-05-03T00:32:44.983 回答
9

我看到了您的功能依赖多参数空数据类型灵活范围类型变量,并为您提供了 Haskell 98 版本!它使用在 hackage 上可用的 HoleyMonoid:

{-# LANGUAGE NoMonomorphismRestriction #-}

import Prelude hiding (id, (.))
import Control.Category
import Data.HoleyMonoid

suc n = later (:[]) . n

zero  = id
one   = suc zero
two   = suc one
three = suc two

buildList = run

测试(随意省略任何类型签名):

> run three "one" "two" "three"
["one","two","three"]
于 2011-05-05T23:42:11.040 回答
4

内联 Martijn 的代码提供了一个非常简单的解决方案:

zero xs = xs
suc n xs x = n (xs ++ [x])
buildList n = n []
于 2011-05-06T09:17:19.323 回答
4

哦,我的... FlexibleContexts ???无单态限制???来吧,伙计们,这不正是 TypeFamilies 的用途吗?

{-# LANGUAGE TypeFamilies #-}
data Zero = Zero
newtype Succ n = Succ n
zero = Zero
one = Succ zero
two = Succ one
three = Succ two
class BuildList n where
    type BL n
    buildListPrefix :: n -> ([String] -> [String]) -> BL n
instance BuildList Zero where
    type BL Zero = [String]
    buildListPrefix Zero h = h []
instance BuildList n => BuildList (Succ n) where
    type BL (Succ n) = String -> BL n
    buildListPrefix (Succ n) h s = buildListPrefix n (h . (s:))
buildList:: BuildList n => n -> BL n
buildList n = buildListPrefix n id
于 2011-05-06T17:07:04.760 回答