Reputation:
I need to generate a list of numbers, which contains of 500
numbers that div 23 x == 7
, (where x
is a number), starting from the 51
such number. I do not know how to finish my programm, so I'd be very happy if anybody could help me. Program cannot take arguments, I mean for example required xs
is not allowed.
required
= do
putStr "Required list is: "
print [c x m n | c <- what goes here?, x <- [1 ..], div 23 x == 7, n <= 500 && m >= 51]
Upvotes: 0
Views: 781
Reputation: 2411
While generating list using list comprehension as dflemstr's answer is usually preferred in this case (including myself). I assume you are new to Haskell so I would like to give a verbose way how you might get your list. The result should be the same.
Note: My code won't be able to put in ghci prompt, you need to create hs file and compile or load using :l from ghci
-- raw is [51, 52, 53, ... to infinity]
lst_raw = [51..]
-- you want only element that make this predicate True so just filter that do not out
lst_flt = filter (\x -> div 23 x == 7) raw
-- above list is infinite, want only first 500 element
mylist = take 500 lst_flt
or you can combine multiple lines to get rid of intermediate bindings that you don't use
mylist = take 500 $ filter (\x -> div 23 x == 7) [51..]
Also just curious on div 23 x part, since div 23 x vs div x 23 is different and it look like div 23 x will never get any value == 7
> take 100 $ map (\x -> x `div` 23) [1..]
[0,0,0,0,0 ... 4,4,4,4]
> take 100 $ map (\x -> 23 `div` x) [1..]
[23,11,7,5,4,3,3 .... 0,0,0,0]
Upvotes: 0
Reputation: 6610
take 500 (drop 50 [x | x <- [1..], div 23 x == 7])
: First generate the list of numbers you want, drop the first 50 (so that you end up with the 51st such number), and then take 500 of them.
As dflemstr said, there is only one number such that div 23 x == 7, so I think you might mean mod x 23 == 7
instead, i.e. the numbers that leave 7 upon division by 23. In that particular case, a better solution is map (\x -> 23 * x + 7) [50 .. 549]
but that's error-prone; I made an off-by-error on my first try!
Upvotes: 1
Reputation: 26147
You can use this:
let theList = take 500 [x | x <- [51..], div 23 x == 7]
print theList
This seems to be a very simple problem, so I might not have understood your description correctly.
Also, there is only one number for which div 23 x == 7
, namely 3 (because 23 / 3 ~= 7
in integer arithmetic). So your list will not contain 500 elements and the program will freeze attempting to find elements of the list.
(I'm offering the full solution to the problem because the asker is probably having a different problem that he failed to describe.)
Upvotes: 3