我尝试制作调用子序列的递归函数,但我遇到了一些错误。
我的代码:
recursive 1 list = subsequences list
recursive n list = subsequences (recursive (n-1) list)
错误:
Occurs check: cannot construct the infinite type: a1 ~ [a1]
Expected type: [a1]
Actual type: [[a1]]
Relevant bindings include
recursive :: a -> t -> [[a1]] (bound at p.hs:6:1)
In the first argument of ‘subsequences’, namely
‘(recursive (n - 1) list)’
In the expression: subsequences (recursive (n - 1) list)
你能帮助我解决这个问题,还是找到另一种方法来调用子序列n次?
抱歉我的英文不好
答案 0 :(得分:5)
我还没有多态递归,所以我想尝试一下。这就是我得到的:
{-# LANGUAGE DeriveFunctor #-}
import Data.List (subsequences)
-- Any multiply-nested list such as a, [a], [[a]], [[[a]]], ...
data MultiList a
= Leaf a
| Nest (MultiList [a])
deriving (Show, Functor)
recursive :: Int -> [a] -> MultiList [[a]]
recursive 1 list = Leaf (subsequences list)
recursive n list = Nest (fmap subsequences (recursive (n-1) list))
答案 1 :(得分:3)
使用singletons非常简单。
{-# LANGUAGE GADTs, DataKinds, TypeFamilies, UndecidableInstances, TemplateHaskell, TypeOperators #-}
import Data.List
import Data.Singletons.TH
import Data.Singletons.Prelude
import qualified GHC.TypeLits as Lit
$(singletons [d| data Nat = Z | S Nat |])
type family Nested n a where
Nested Z a = a
Nested (S n) a = [Nested n a]
subsequenceses :: Sing n -> [a] -> [Nested n a]
subsequenceses SZ xs = xs
subsequenceses (SS sn) xs = subsequences (subsequenceses sn xs)
type family Lit i where
Lit 0 = Z
Lit n = S (Lit (n Lit.- 1))
type SLit n = Sing (Lit n)
main = print $ subsequenceses (sing :: SLit 2) [1..2]
subsequenceses (sing :: SLit 0) xs
是xs
subsequenceses (sing :: SLit 1) xs
是subsequences xs
subsequenceses (sing :: SLit 2) xs
是subsequences (subsequences xs)
等等。
答案 2 :(得分:1)
如果我用1调用你的函数,它将返回一个元素列表列表。如果我用2调用它,它将返回元素列表的列表列表。在依赖类型的语言中,这很好,但Haskell不依赖于类型,因此您需要以其他方式表示结果,在结果类型中对深度进行编码。