简体   繁体   中英

Infinite list of powers using subset of Haskell

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 eg

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, ie 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.

This is a recursion question.

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

(Are you allowed to use : ?)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM