Adding to other answers,
Since show
returns a java.lang.String
, it is not possible to show infinite lists. So I thought I could write a different version of show to return a [Char]
instead. This is what I have come up with and it is working.
frege> :paste
class AltShow a where
altshow :: a -> [Char]
instance AltShow AltShow a => [a] where
altshow [] = []
altshow xs = concat $ (['['] : intersperse [','] ys) ++ [[']']] where
ys = map altshow xs
instance AltShow Int where
altshow = unpacked <~ show
intersperse :: a -> [a] -> [a]
intersperse _ [] = []
intersperse _ (x:[]) = [x]
intersperse sep (x : y : []) =
x : sep : y : []
intersperse sep (x : y : rest) =
x : sep : y : sep : intersperse sep rest
:q
Interpreting...
frege> altshow [1, 10, 2, 234]
res3 = ['[', '1', ',', '1', '0', ',', '2', ',', '2', '3', '4', ']']
frege> :t res3
res5 :: [Char]
frege> packed res3
res6 = [1,10,2,234]
frege> :t res6
res7 :: String
Now the code in the question becomes similar to Haskell and it is not exploding with OutOfMemoryError:
frege> :paste
foo = take 10 $ altshow $ numbersFrom 1 where
numbersFrom start = start : numbersFrom (start + 1)
:q
Interpreting...
frege> foo
res9 = ['[', '1', ',', '2', ',', '3', ',', '4', ',', '5']
frege> packed foo
res11 = [1,2,3,4,5
take 10
cannot be applied to the result ofshow
. Henceunpacked
is used to first convert fromString
to[Char]
and thentake 10
is applied on the list. – Recha