Search code examples
haskellrecursionsubsequence

How recursively call subsequences in haskell


I tried to make recursive function which call the subsequences and I had got some errors.

My Code:

recursive 1 list = subsequences list
recursive n list = subsequences (recursive (n-1) list)

Error:

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)

Could you help me to solve this problem or find another way to call subsequences n times?

Sorry for my bad English


Solution

  • I haven't worked with polymorphic recursion much, so I wanted to try this. Here's what I got:

    {-# 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))