# Another fold question

Patty Fong patty_jf at hotmail.com
Thu Nov 6 04:27:31 EST 2003

```Having struglled over this for the better part of a day and only becoming
more frustrated the more i try to understand it, i once again seek help :)

I understand how basic folds work, i.e foldr replaces (:) with some
parameter and [] by another i.e
foldr (+) 0 [1,2,3] becomes 1+(2+(3+0))

I also understand how to write my own fold function. What i don't understand
quite is how to use them. given this data type and this fold function i
wrote:

data Music
= Note Pitch Octave Duration
| Silence Duration
| PlayerPar Music Music
| PlayerSeq Music Music
| Tempo (Ratio Int) Music
data Pitch = Cf | C | Cs
type Octave = Int
type Duration = Ratio Int

foldMusic :: (Pitch -> Octave -> Duration -> a)
-> (Duration -> a)
-> (a -> a -> a)
-> (a -> a -> a)
-> (Ratio Int -> a -> a)
-> Music
-> a

foldMusic n _ _ _ _ (Note pitch octive duration) = n pitch octive duration
foldMusic _ s _ _ _ (Silence duration) = s duration
foldMusic n s p1 p2 t (PlayerPar partOne partTwo) = p1 (foldMusic n s p1 p2
t partOne)(foldMusic n s p1 p2 t partTwo)
foldMusic n s p1 p2 t (PlayerPar partA partB) = p2 (foldMusic n s p1 p2 t
partA)(foldMusic n s p1 p2 t partB)
foldMusic n s p1 p2 t (Tempo rate part) = t rate (foldMusic n s p1 p2 t
part)

I understand that when i use the foldMusic function i need to pass it 5
parameters.  given the type signiature, why can i pass (+) as a parameter
for p1 but not for n, what determines what can be passed as a parameter,
because they all have the return type a??

I attempted to create a function that utilises the foldMusic function that
counts the number of notes:

count_notes :: Music -> Integer
count_notes = foldMusic (\_-> \_ -> \_ -> 1) (\_ -> 0) (+) (+) (\_ -> \_ ->
0)

it appears to work, i think. Yet i'm still not certain of how it does so.

This confuses me,
Is there anyway to represent other fold functions in a tree like
representation as foldr (+) 0 would appear as such?
+
1 \
+
2 \
+
3 \
0

Regards,
confused Patrick

_________________________________________________________________
Hot chart ringtones and polyphonics. Go to
http://ninemsn.com.au/mobilemania/default.asp

```