[Haskell-cafe] A function using List and Tuple
jotajota
jotajota at hetnet.nl
Mon Jun 19 10:40:21 EDT 2006
Hi
On 6/19/06, Sara Kenedy <sarakenedy at gmail.com> wrote:
> Hello,
>
> I want to creat a function sumList as below examples:
> sumList [("s1",2),("s2",4),("s3",3),("s4",2)] = ("#", 1/2 + 1/4 + 1/3 + 1/2)
> sumList [("s1",2),("s2",4),("s3",3) = ("#", 1/2 + 1/4 + 1/3)
>
> I attempted it as following:
>
> sumList :: (Fractional a) => [(String,a)] -> (String, a)
> sumList [] = ???
> sumList (x:xs) = ("#", 1/(snd x) + 1/snd(sumList xs))
>
> I know this function cannot give the correct answer (even if I define
> sumList []), but I did not find the right way.
> If anyone can give me a suggestion, I really appereciate for that. Thanks.
>
Yo can use the foldr function:
sumList a = ("#",foldr suma 0 a )
where suma (s,x) y = 1/x + y
Juan Jose
More information about the Haskell-Cafe
mailing list