0
votes

I need to make a function "powers" that takes a number n and returns the infinite list of that number to the power of every number e.g.

powers 2 = 2,4,8,16,32......

I need to do this using very specific subset of the language where my only available built in functions are: div, mod, even, odd, head, tail, not, null, length, reverse, elem, map, filter, foldr, sum, product, take, drop, takewhile, dropWhile, zipWith and from.

the subset also has no ^ operator.

there are some further important constraints:

  • the code must not exceed 1 line of more than 80 characters
  • no "helper functions" allowed, i.e i cannot write another function to use within this definition.

So far my thinking is along these lines:

powers = \n -> map (\x -> "some function to get n to the power of x") (from 1)

but i cant figure out how to get the function to do this without a helper function.

for example if i was to use a function inflist that returned an infinite list of the number x then i could just do the following.

powers = \n -> map (\x -> product(take x (inflist n))) (from 1)

but i cant do this or anything like it because i couldn't use that function.

Sorry if the notation is a different to normal haskell, its a very strict core haskell subset that uses this notation.

2
What operators are allowed exactly? The problem gets a lot harder (but more fun!) if you can't use * and instead have to create a list of 2s of the right length to put into product. That, in turn is tricky if you cannot use the list consing operator : and the empty list, or the </==/<= operators for checking the length...yatima2975

2 Answers

3
votes

This is a recursion question.

powers n = n : map (* n) (powers n)

(Are you allowed to use :?)

0
votes

This was fun and funner when the insight came. Generate successively longer repetitions of 2 in lists with

[ [ 2 | y <- [1..x]] | x <- [1..]]

Then take the product of each list.

map product [ [ 2 | y <- [1..x]] | x <- [1..]]

Be sure to use take x before an invocation I struggled with a mod and multiple mod functions to limit lists.

If iterate were allowed.

take 24 $ iterate (2*) 2

would generate the list.

Edit 4/4/2018

An infinite recursive function, may be what you are looking for to fill out your function. It might be:

pow l = l ++ pow [(last l * 2)]

To produce a list it is absolutely necessary to assemble a list and it is necessary to use the last element of the list to calculate the next in sequence. This must also be run with take. Also the command following starts the list with 1. It can be started with any number such as 64 or 63. I tried passing the last value as a parameter but then the function would not generate a list. There is a choice, use ':' instead of '++' but it will produce each element in a list. To produce a list of values instead of a list of lists used 'concat $ ' before 'take' to clean it up.

take 10 $ pow [1]