0

I have written the following code:

hosum :: (Int->Int)->(Int->Int)     
hosum f 0 = 1
hosum f n = afunction f (-abs(n)) (abs(n))


afunction :: (Int->Int)->Int->Int->Int
afunction f a z
    |a==z
        = 0
    |otherwise
        = afunction f (a+1) z + afunction f a z

to find the sum of f(i) from -|n| to |n|.. Where is my mistake?

3
  • 7
    You never call f. Try deleting the type signatures and see what type GHC infers for your functions (the f argument will be completely polymorphic). Commented Apr 3, 2015 at 0:50
  • as @jcast said: you just need a summand more for your otherwise case but while manual recursion is nice to start I would recommend to think about how to do this with map and sum instead - PS what is the hosum for? I thnk you can just delete this here - also you might try to find better function names and give an example of how you want to call your functions - it's a bit strange here Commented Apr 3, 2015 at 5:27
  • @jcast i don't understand what you are saying just because i am a beginner with haskell .. this exercise is for my class and my professor has told us to make this function starting with the following: hosum :: (Int->Int)->(Int->Int) hosum f n . something more clear would be helpfull Commented Apr 3, 2015 at 8:40

1 Answer 1

1

As pointed out in the comments, your code never calls the f function. There are several other things in your code that I don't understand:

  1. hosum f 0 = 1. Why is it one for any f. Shouldn't it be f 0?

  2. In afunction, why is the result 0 if a == z. If the range is inclusive, it should be zero only if a > z.

  3. afunction in the otherwise case calls itself twice. Why doesn't it apply f to a and calls afunction f (a + 1) z only?

Now about a correct solution. The easiest(and idiomatic) way to implement it is to use standard sum and map functions. It gives a one-liner(if we don't count type signature):

hosum :: (Int -> Int) -> Int -> Int
hosum f n = sum $ map f [-abs(n)..abs(n)]

In plain English, this function takes a list of all numbers from -abs(n) to abs(n), applies f to each of them and sums them up. That's exactly what the problem statement tells us to do.

Sign up to request clarification or add additional context in comments.

2 Comments

Furthermore, what would i do, if i had a list with function and one other list to make a new list where each element of the one list, map with the other element of the other list ? For example, apply [(^2),(^3),(^4),(2^)] [10] = [100,1000,1024,10000]. the length of each list could be bigger
@ΔιονυσιαΑγαλιώτη You can use list comprehensions. Something like this: [f x | f <- [(2*), (2+)], x <- [1, 2]] = [2, 4, 3, 4].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.