I'm struggling with the following function:
The following declaration works:
data DividedResult = Result Integer | DividedByZero deriving (Eq, Show)
dividedBy num denom =
let
(count,remainder,success) = x num denom 0
in if success then (Result count) else DividedByZero
where
x num denom count
| denom == 0 = (0,0,False)
| num | otherwise = x (num - denom) denom (count + 1)
data DividedResult = Result Integer | DividedByZero deriving (Eq, Show)(snip)
*Lib> :t dividedBy(snip)
dividedBy :: (Num b, Ord b) => b -> b -> DividedResult
However, if I try to add the type declaration line:
dividedBy :: (Num a, DividedResult b) => a -> a -> b
Could someone please kindly point out my mistake and suggest a type declaration line that works?
On 16 Jul 2018, Black Swan wrote:
data DividedResult = Result Integer | DividedByZero deriving (Eq, Show)(snip)
*Lib> :t dividedBy
dividedBy :: (Num b, Ord b) => b -> b -> DividedResult
However, if I try to add the type declaration line:
dividedBy :: (Num a, DividedResult b) => a -> a -> b(snip)
Could someone please kindly point out my mistake and suggest a type declaration line that works?
Beyond the issues with the code as presented, DividedResult is just an algebraic datatype. The constraint syntax you're using in the type
signature is for classes, not types: classes simply limit the types that
can be used to fill in the type variables like a and b. Also you do need
the Ord because that's what "<" needs. It might help if you back up and
let us know what you're hoping this type signature will achieve that the inferred one doesn't. It may help to note that in many places where in
C++ or whatever you might use a thing called a class, in Haskell it will still simply be a type, with classes being at another step removed and
not always needed in the same way.
-- Mark
On Mon Jul 16 21:05:06 2018 Mark Carroll wrote:(snip)
On 16 Jul 2018, Black Swan wrote:
(snip)*Lib> :t dividedBy
dividedBy :: (Num b, Ord b) => b -> b -> DividedResult
I am starting to get the hang of it. Just figured out that the declaration that I needed was:
dividedBy :: (Num n, Ord n) => n -> n -> DividedResult
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 296 |
Nodes: | 16 (2 / 14) |
Uptime: | 20:14:02 |
Calls: | 6,646 |
Calls today: | 1 |
Files: | 12,190 |
Messages: | 5,327,391 |