to generate integer partitions.
variation_models' nlocations =
let location_list = [1..nlocations-4]
in [[x1, x2, x3, x4, x5] |
x1 <- location_list,
x2 <- location_list,
x3 <- location_list,
x4 <- location_list,
x5 <- location_list,
both_conditions (adds_up_to nlocations) num_orderedq [x1, x2, x3, x4, x5]]
It seems to have better memory characteristics then the more generalvariation_models 5 15
[1,1,1,1,11]
我想写这个函数
但有任何数量的X。我想
variation_models ncars nlocations =
filter (both_conditions (adds_up_to nlocations) num_orderedq) $
replicateM ncars [1..nlocations-ncars+1]
的有效答案 .我现在的尝试是
不过
replicateM似乎使函数占用了越来越多的内存。
import Control.Monad
orderedq f [] = True
orderedq f (x:[]) = True
orderedq f (x:y:zs) = f x y && orderedq f (y:zs)
num_orderedq = orderedq (<=)
adds_up_to n xs = n == sum xs
both_conditions f g xs = f xs && g xs
variation_models ncars nlocations =
filter (both_conditions (adds_up_to nlocations) num_orderedq) $
replicateM ncars [1..nlocations-ncars+1]
variation_models' nlocations =
let location_list = [1..nlocations-4]
in [[x1, x2, x3, x4, x5] |
x1 <- location_list,
x2 <- location_list,
x3 <- location_list,
x4 <- location_list,
x5 <- location_list,
both_conditions (adds_up_to nlocations) num_orderedq [x1, x2, x3, x4, x5]]
. replicateM
integer_partitions :: Int -> Int -> [[Int]]
integer_partitions 0 _ = []
integer_partitions 1 n = [[n]]
integer_partitions k n =
do x <- [1..n - k + 1]
map (x:) (integer_partitions (k - 1) (n - x))
我想写这个函数variation_models' nlocations = let location_list = [1...nlocations-4] in [[x1, x2, x3, x4, x5] 。