haskell - Variable List Comprehension Length -
haskell - Variable List Comprehension Length -
i'm generating list of lists via list comprehension, have no thought how create sub list's length variable using parameter. input next tuple (first, second) , integer z:
z = 1:
[[a] | <- [first..second]] z = 2:
[[a, b] | <- [first..second], b <- [first..second]] z = 3:
[[a, b, c] | <- [first..second], b <- [first..second], c <- [first..second]]
you can utilize replicatem task. it's defined as
replicatem :: monad m => int -> m -> m [a] replicatem n m = sequence (replicate n m) the connection here turn list comprehension do notation:
[[a] | <- [first..second]] == <- [first..second] homecoming [a] [[a, b] | <- [first..second], b <- [first..second]] == <- [first..second] b <- [first..second] homecoming [a, b] [[a, b, c] | <- [first..second], b <- [first..second], c <- [first..second]] == <- [first..second] b <- [first..second] c <- [first..second] homecoming [a, b, c] to create more clear, let's replace [first..second] m:
do allow m = [first..second] <- m b <- m c <- m homecoming [a, b, c] so here can see m getting replicated n times, hence replicatem. let's see how types line too:
replicatem :: monad m => int -> m -> m [a] m ~ [] replicatem_list :: int -> [a] -> [[a]] if need on arbitrary lists, not repeating same list, can utilize sequence on it
haskell list-comprehension
Comments
Post a Comment