Reputation: 2924
This is probably very easy, but I cannot figure out how to do the equivalent of Python's
[0]*n
in Haskell, in order to get a list with n zeros.
[0]*n
doesn't work. Am I obliged to do something like: [0 | x <-[1..5]]
?
Upvotes: 4
Views: 6929
Reputation: 36349
Another possibility:
import Data.Monoid
zeroes = 5 * [0] where (*) = mtimes
Upvotes: 0
Reputation: 48746
You can do this:
λ> take 5 (repeat 0)
[0,0,0,0,0]
Or as @obadz points out, this is even more concise:
λ> replicate 5 0
[0,0,0,0,0]
I personally don't like the python syntax. *
means multiplication but it does something else in your case. But that's just my opinion :).
Upvotes: 10
Reputation: 67507
you can define it yourself (as a toy example)
(*) :: [a] -> Int -> [a]
(*) xs n = take n $ cycle xs
so you can have
Prelude> [0]*5
[0,0,0,0,0]
Prelude> [0,1]*5
[0,1,0,1,0]
obviously, by redefining existing operators have "side effects"
Prelude> 4*4
<interactive>:169:1:
Non type-variable argument in the constraint: Num [a]
(Use FlexibleContexts to permit this)
When checking that `it' has the inferred type
it :: forall a. Num [a] => [a]
or perhaps python
interpretation is replicate the list n times (instead of picking n elements from the cycled list elements). In that case you can define it as
(*) :: [a] -> Int -> [a]
(*) xs n = concat $ replicate n xs
Prelude> [0]*4
[0,0,0,0]
Prelude> [0,1]*4
[0,1,0,1,0,1,0,1]
obviously, this is a toy example and you may want to define another operator or simply a function for this.
Upvotes: -1