Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to Turn this recursive haskell function into a map call?

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

I'm looking for a way to use the map function and get rid of this recursive function. Is that possible and if so, how do I do it?

like image 760
rfgamaral Avatar asked Dec 18 '08 03:12

rfgamaral


2 Answers

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.

like image 111
Apocalisp Avatar answered Oct 24 '22 05:10

Apocalisp


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"
like image 39
Norman Ramsey Avatar answered Oct 24 '22 04:10

Norman Ramsey