def get_N_Partition_Permutations(xs, n):
if n == 1:
return [[xs]]
acc = []
for i in xrange(1,len(xs)):
acc += [[xs[:i]] + j for j in get_N_Partition_Permutations(xs[i:], n-1)]
return acc
Я пытаюсь реализовать вышеприведенную функцию (которая находится на Python) в haskell ниже.Ошибка бесконечного типа в haskell при попытке перевести функцию python в haskell. Зачем?
getNPartitionPermutations :: [a] -> Int -> [[[a]]]
getNPartitionPermutations xs 1 = [[xs]]
getNPartitionPermutations xs n = iter xs 1 []
where iter ys i acc
| length xs == i = acc
| otherwise =
iter ys (i+1) (elem':acc)
where elem' = map (\x -> [(take i ys)]:x) rec'
rec' = getNPartitionPermutations (drop i ys) (n-1)
У меня возникает странная ошибка, которую я не совсем понимаю. Почему этот код работает в python, но не в haskell? Сообщение об ошибке ниже
partitionArr.hs|23 col 104 error| Occurs check: cannot construct the infinite type: a ~ [[a]]
Expected type: [[[a]]]
Actual type: [a]
Relevant bindings include
acc :: [[[[[a]]]]] (bound at partitionArr.hs:21:19)
ys :: [a] (bound at partitionArr.hs:21:14)
iter :: [a] -> GHC.Types.Int -> [[[[[a]]]]] -> [[[[[a]]]]] (bound at partitionArr.hs:21:9)
xs :: [[[a]]] (bound at partitionArr.hs:20:27)
getNPartitionPermutations :: [[[a]]] -> GHC.Types.Int -> [[[[[a]]]]]
(bound at partitionArr.hs:19:1)
In the first argument of ‘Algo.getNPartitionPermutations’,
namely ‘(GHC.List.drop n ys)’
In the second argument of ‘(GHC.Base.$!)’,
namely ‘Algo.getNPartitionPermutations (GHC.List.drop n ys) (n
GHC.Num.- 1)’
partitionArr.hs|20 col 39 error| Occurs check: cannot construct the infinite type: a ~ [[a]]
Expected type: [a]
Actual type: [[[a]]]
Relevant bindings include
iter :: [a] -> GHC.Types.Int -> [[[[[a]]]]] -> [[[[[a]]]]] (bound at partitionArr.hs:21:9)
xs :: [[[a]]] (bound at partitionArr.hs:20:27)
getNPartitionPermutations :: [[[a]]] -> GHC.Types.Int -> [[[[[a]]]]]
(bound at partitionArr.hs:19:1)
In the first argument of ‘iter’, namely ‘xs’In the expression: iter xs 1 []
Редактировать: Потому что я не был чист. Функция python возвращает все возможные n разделов списка. поэтому параметры [1,2,3,4], 2 дают [[[1], [2,3,4]], [[1,2], [3,4]], [[1,2,3] ] [4]]]
тип подписи функции Haskell является [а] -> Int -> [[[а]]]
Сообщение * говорит *, что у вас есть несоответствующие уровни вложенности списка. Попробуйте добавить явную подпись типа к вашей функции; то GHC будет знать, что вы * предназначили * тип, который должен быть, и мог бы дать вам лучшую идею о том, где ошибка. – MathematicalOrchid
Моя личная теория заключается в том, что вам не нужны квадратные скобки в 'map (\ x -> [(take n ys)]: x)', но я этого не проверял. – MathematicalOrchid
только для записи: отсутствует определение 'subdivideList' в вашем коде Python. –