haskell:在无限列表的有限列表上重复乘法序列器

时间:2016-02-03 05:18:21

标签: haskell stack-overflow infinite

给定无限列表的有限列表,或者无限列表的有限列表,如果您愿意,我想应用乘法运算符(~>)(~~>)(>*>)服从分配财产:

[[a], [b], [c]] >*> [[d], [e]] == [[a, d], [a, e], [b, d], [b, e], [c, d], [c, e]]

这也适用于(~>)(~~>)转置表示。

然后我想“重复”这个乘法运算符“forever``

以下是我的尝试,所有这些都是由于共同依赖(我认为)最终导致堆栈溢出或永不终止。

示例1:

import Data.Maybe(listToMaybe)
import Control.Monad(liftM2)

type A = [[Int]]

a :: A
a = [[1]]

-- Building finite lists of infinite lists:
(~>) :: A -> A -> A
(~>) = liftM2 (++)

forever1 :: A -> A
forever1 p = p ~> forever1 p

forever2 :: A -> A
forever2 p = forever2 p ~> p

示例2:

-- Building infinite lists of finite lists:
(~~>) p q = mx q p ++ mx p q
    where innerLen = maybe 0 length . listToMaybe
          mx a = map (concatMap $ replicate $ innerLen a)

forever3 :: A -> A
forever3 p = p ~~> forever3 p

forever4 :: A -> A
forever4 p = forever4 p ~~> p

{-
forever1 p = do
    x <- p
    y <- do
        x' <- p
        y' <- do
            ...
    return $ x ++ y

forever1 p =
    p >>= \x1 -> p >>= \x2 -> p >>= ... >>= \xn -> return concat [x1, x2, ... xn]
-}

示例3:

u = undefined

type ActionFn a = a -> (Action a, a)
data Action a = None | A { act :: ActionFn a }
newtype Program a = P { actions :: [Action a] }

(>>>) :: Action a -> Action a -> Action a
(>>>) None q = q
(>>>) (A f) g = A $ \a -> let (h, b) = f a in (h >>> g, b)

(>*>) :: Program a -> Program a -> Program a
(>*>) (P ps) (P qs) = P $ zipWith (>>>) (mul qs ps) (mul ps qs)
    where mul other = concatMap (replicate $ length other)

basic :: ActionFn a -> Program a
basic = P . return . A

idle :: Program a
idle = basic $ \a -> (None, a)

forever5 :: Program a -> Program a
forever5 p = p >*> forever5 p

testF5 = map (const "x") $ actions $ forever5 idle

列表实际上并不是由Int组成,而是由a -> a组成。

我的问题可能以某种方式解决吗?如果是这样 - 怎么样? 或者是不可能的?

0 个答案:

没有答案