Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all subnumbers of a number in haskell

Tags:

haskell

I would like to get all sub numbers of a number from a particular side.

In the case of the number 1234, the sub numbers from the left side are:

1, 12, 123, 1234

I implemented it with:

tail . inits $ show 1234

This way I get all the sub numbers in [[Char]] format.

["1","12","123","1234"]

I tried to convert them to Integer, with the following line.

map read . tail . inits $ show 1234

But I get the following error

[*** Exception: Prelude.read: no parse

What am I doing wrong?


1 Answers

because the interpreter does not know what type you want back

this will work:

λ> map read . tail . inits $ show 1234 :: [Int]
[1,12,123,1234]

of course you can just add a type-signature as well (most likely in your code file):

subnums :: Int -> [Int]
subnums = map read . tail . inits . show

in ghci:

λ> subnums 1234
[1,12,123,1234]

and a nice exercise can be to do this without show/read:

subnumbers :: Int -> [Int]
subnumbers 0 = []
subnumbers n =
  n : subnumbers (n `div` 10)

Can you solve the problem with the order here?

like image 68
Random Dev Avatar answered Nov 29 '25 21:11

Random Dev