简体   繁体   中英

Haskell division algorithm function

my professor assigned me a pretty basic lab that is mostly done. Essentially what it should do resembles divMod. It should output the quotient and the remainder using a recursive function. Below is the code. I am not quite sure what is going on syntax wise also if someone could maybe explain what might go in the "Fill this in" part. I understand that a < b is the simple case meaning the quotient is zero and the remainder is a. So q = 0 and r = a. This will eventually be achieved by repeatedly subtracting b from a. Let 17 be a and 5 be b, so as follows: 17-5=12 then 12-5=7 then 7-5=2 which means the quotient is 3 and remainder is 2. So I understand whats going on I just cannot write it in haskell. Thanks for any help. Sorry for the super lengthy question.

divalg :: Int -> Int -> (Int, Int)
divalg a b | a < b = --Fill this in--
           | otherwise = let (q, r) = divalg (a - b) b 
            in --Fill this in--

From the type signature, you can see that divalg takes two Int s and returns a pair of Int s, which you correctly identified as the quotient and remainder. Thus in the base case (where a < b ), you should do that: return a tuple containing the quotient and remainder.

In the recursive case, the recursive call is already written. When thinking about recursion, assume the recursive call "does the right thing". In this case, the "right thing" is to return the quotient and remainder of (ab)/b . I'll leave the math to you, but the basic idea is that you need to modify the tuple (q,r) to get a new tuple containing the quotient/remainder for a/b . How do I know this is the right thing to do? Because the type signature told me so.

In short, your code will look something like this:

| a < b = (___, ___)
| otherwise = let ...
 in (___, ___)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM