[Haskell-beginners] question on evaluation

Theodore Lief Gannon tanuki at gmail.com
Sat Jan 9 23:54:41 UTC 2016


Here's why you're getting the longer repetition first:

buildLenList "bang"
= buildLenList (_:"ang")
= [1 + length "ang"] ++ buildLenList "ang"
= [4] ++ buildLenList "ang"
(...) = [4, 3, 2, 1]

And the reason calling myReverse on that doesn't give you [1, 2, 3, 4] is
that you're reversing a different list every time:

blowup "bang"
= blowup ('b':"ang")
= myRepeat 'b' (head (myReverse (buildLenList ('b':"ang"))) ++ blowup "ang"
= myRepeat 'b' (head (myReverse [4, 3, 2, 1]) ++ blowup "ang"
= myRepeat 'b' (head [1, 2, 3, 4] ++ blowup "ang"
= myRepeat 'b' 1 ++ blowup "ang"
= "b" ++ blowup "ang"
= "b" ++ blowup ('a':"ng")
= "b" ++ myRepeat 'a' (head (myReverse (buildLenList ('a':"ng"))) ++ blowup
"ng"
= "b" ++ myRepeat 'a' (head (myReverse [3, 2, 1]) ++ blowup "ng"
= "b" ++ myRepeat 'a' (head [1, 2, 3] ++ blowup "ng"
(...)

Since you only asked for help with how it evaluates, I'll withhold further
spoilers. :)  However, I strongly recommend getting more comfortable using
the (:) operator for construction instead of just pattern matching; in a
couple of your functions it would be a better tool than (++). Also,
"at-patterns" are great:

blowup l@(x:xs) =  myRepeat x (head (buildLenList l)) ++ blowup xs

On Sat, Jan 9, 2016 at 7:21 AM, Fabien R <theedge456 at free.fr> wrote:

> Hello,
>
> I want to define a function blowup that takes "bang" as input and returns
> "baannngggg".
> I come up with these functions;
>
> myReverse :: [a] -> [a]
> myReverse [] = []
> myReverse (x:xs) = myReverse xs ++ [x]
>
> buildLenList :: String -> [Int]
> buildLenList "" = []
> buildLenList (_:xs) = [1 + length xs ] ++ buildLenList xs
>
> myRepeat :: Char -> Int -> String
> myRepeat x 0 = []
> myRepeat x n = [x] ++ myRepeat x (n - 1)
>
> blowup :: String -> String
> blowup [] = []
> blowup (x:xs) =  myRepeat x (head ( (buildLenList (x:xs)))) ++ blowup  xs
>
> With this code, blowup "bang" returns "bbbbaaanng".
>
> So I thought to insert myReverse between head and buildLenList but in that
> case, the result is only "bang".
>
> It seems that the evaluation of buildLenList is not working as I thought.
> I tried to debug that using ghci debugger but failed (still learning).
> Can someone explain how the evaluation is done here ?
>
> --
> Fabien
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160109/46db73d9/attachment.html>


More information about the Beginners mailing list