views:

426

answers:

2

This is my code:

type HoraAtendimento = (String, Int, Int)

htmlHAtendimento :: [HoraAtendimento] -> Html
htmlHAtendimento [] = toHtml ""
htmlHAtendimento ((da,hia,hfa):[]) = toHtml da +++ "feira "
                                     +++
                                     show hia +++ "h - " +++ show hfa +++ "h"
htmlHAtendimento ((da,hia,hfa):r) = toHtml da +++ "feira "
                                    +++
                                    show hia +++ "h - " +++ show hfa +++ "h, "
                                    +++
                                    htmlHAtendimento r

And I'm looking for a way to use the map function and get rid of this recursive function.

If this is possible, can anyone help me out?

+8  A: 

Look at the type of map. It is (a -> b) -> [a] -> [b]. That doesn't look like your type, which is [a] -> b. That's not a map, that's a fold.

The higher-order function you want to look at is foldr. See Hoogle.

Something like...

htmlHAtendimento :: [HoraAtendimento] -> Html
htmlHAtendimento [] = toHtml ""
htmlHAtendimento l = foldr1 (+++) $ intersperse ", " $ map f l
  where f (da, hia, hfa) = toHtml da
                           +++ "feira "
                           +++ show hia
                           +++ "h - "
                           +++ show hfa
                           +++ "h"

I don't know if that's correct, but that's in the right direction.

Apocalisp
That's one function that I find very confusing and I could never learn it... Could you give me an example with my code? I have a bunch of similar functions and if I could just see one example, I'll probably manage the others...
Nazgulled
Actually since the list is nonempty you're better off with foldl1 or foldr1. Example below. ---NR
Norman Ramsey
Nice, "intersperse". +1 :-)
ShreevatsaR
You will want to learn to use folds, since they are an extremely useful abstraction. Practice rewriting some simple recursions into folds. Look at the source code for foldr and foldl.
Apocalisp
Ah yes, the old late edit does the trick. 'intersperse' considered necessary, indeed. Well done!
Norman Ramsey
+1  A: 

You want to fold over a nonempty list. This code might do the trick:

type HoraAtendimento = (String, Int, Int)

htmlHAtendimento :: [HoraAtendimento] -> Html
htmlHAtendimento [] = toHtml ""
htmlHAtendimento l = foldl1 (+++) $ map convert l
  where convert (da,hia,hfa) = toHtml da +++ "feira " +++
                               show hia +++ "h - " +++ show hfa +++ "h"
Norman Ramsey
That doesn't handle the ", " mess.
ShreevatsaR
Whoops, quite right.
Norman Ramsey