Reputation: 13
My code works. I just would like to know if it is possible to just add something in an instance declaration to be checked first before using the default implementation, instead of having to copy the code. An example:
class (Eq a, Ord a, Show a, Num a) => Fibo a where
fib :: a -> a
fib n
| n == 0 = 0
| n == 1 = 1
| otherwise = fib (n-1) + fib (n-2)
instance Fibo Integer where
fib n
| n < 0 = -1
| n == 0 = 0
| n == 1 = 1
| otherwise = fib (n-1) + fib (n-2)
But can it also be written in a way where I dont have to re-implement the whole function? Something like:
instance Fibo Integer where
fib n
| n < 0 = -1
| otherwise = default
Or is there any other way to do without using the same code in two places?
The Solution is NOT to change the default implementation!
Upvotes: 0
Views: 104
Reputation: 2066
Just put the common code to a helper function:
foo::(Eq a, Ord a, Show a, Num a) =>a -> a
foo n
| n == 0 = 0
| n == 1 = 1
| otherwise = foo (n-1) + foo (n-2)
class (Eq a, Ord a, Show a, Num a) => Fibo a where
fib :: a -> a
fib = foo
instance Fibo Integer where
fib n
| n < 0 = -1
| otherwise = foo n
Upvotes: 5