Reputation: 969
My haskell code goes as follows :
module Lain where
let value = 0
divideBy ::(Ord a, Num a)=>a -> a -> a
divideBy _ 0 = 0
divideBy num den
| (num - den) >= 0 = do
value = value + 1
return divideBy (num-den) den
| otherwise = value
The error goes on loading the haskell Lain.hs file is :
app/Lain.hs:18:1: error:
parse error (possibly incorrect indentation or mismatched brackets)
Failed, modules loaded: none.
Not able to interpret where I am going wrong, seems to me more of a logical mistake. My code wants to print the quotient given numerator and denominator. Please help as to what is exactly my mistake. Thanks in advance.
Upvotes: 0
Views: 45
Reputation: 54981
value = value + 1
isn’t a valid statement in a do
block. The only valid statements are:
A variable binding: let pattern = expression
A monadic binding: pattern <- expression
An expression that evaluates to a monadic action
However, you don’t need a do
block because you don’t need monadic side effects to implement this function. Furthermore, return
isn’t like return
in an imperative language—it’s not a keyword that returns from the current function, but a function that creates an action that returns a value. It looks like your intent with value = value + 1
was to mutate value
, but there are no mutable variables in Haskell. (There are mutable reference types such as IORef
, but you don’t need them here.)
So one solution is to simply use an expression:
divideBy :: (Ord a, Num a) => a -> a -> a
divideBy _ 0 = 0
divideBy num den
| num - den >= 0 = 1 + divideBy (num - den) den
| otherwise = 0
This says exactly what it means: the quotient of num
and den
is 0
if den
is 0
; if num - den >= 0
, then it’s 1 more than the quotient of num - den
and den
; otherwise it’s 0
.
Upvotes: 1