-- core function; read from bottom to topf::Int->Intf=sum-- Sum up the squares.map((^2)-- Compute squares.read-- Convert digit strings to Ints.(:[]))-- Explode number string to list of digit strings.show-- Convert input number to string-- This is a folding pattern with a tricky break condition,-- depending on the list element and the accumulator.foldP::(a->b->b)->(a->b->Bool)->b->[a]->bfoldPfpacc[]=accfoldPfpacc(x:xs)|pxacc=acc|otherwise=foldPfp(fxacc)xs-- Cut off a list's tail, once a number is repeating.-- (reverts the preserved part of the list)cut::Eqa=>[a]->[a]cut=foldP(:)elem[]-- fold by appending and checking if x is already in list-- Iterate the core function, cut the result list and check if the final-- result is 1.isHappy::Int->BoolisHappy=(==1).head.cut.iteratefmain=print$filterisHappy[1..200]
Note that Haskell function composition with the (.) operator is read from right to left (or from bottom to top, respectively). The hardest part for FP is folding with a non-trivial break condition, here.
And now that I have learned a simpler break condition for the problem, it is easier:
f::Int->Intf=sum-- Sum up the squares.map((^2)-- Compute squares.read-- Convert digits to Ints.(:[]))-- Explode number string to list of digit strings.show-- Convert input number to stringisHappy::Int->BoolisHappyn|n==4=False|n==1=True|otherwise=isHappy(fn)main=print$filterisHappy[1..200]
On the other hand, I like the possibility of my original code to see the list of intermediate results to get a feeling for the problem.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Adding a solution in Haskell:
Note that Haskell function composition with the (.) operator is read from right to left (or from bottom to top, respectively). The hardest part for FP is folding with a non-trivial break condition, here.
And now that I have learned a simpler break condition for the problem, it is easier:
On the other hand, I like the possibility of my original code to see the list of intermediate results to get a feeling for the problem.