Skip to content

Chapter 1#520

Open
raishovan wants to merge 1 commit intokowainik:mainfrom
raishovan:Chapter1
Open

Chapter 1#520
raishovan wants to merge 1 commit intokowainik:mainfrom
raishovan:Chapter1

Conversation

@raishovan
Copy link
Copy Markdown

Solutions for Chapter 1

cc @vrom911 @chshersh

Copy link
Copy Markdown
Member

@vrom911 vrom911 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work! Thanks for taking your time to finish the Chapter ๐Ÿ˜Š

Comment thread src/Chapter1.hs
-- DON'T FORGET TO SPECIFY THE TYPE IN HERE
lastDigit n = error "lastDigit: Not implemented!"
lastDigit :: Int -> Int
lastDigit x = mod x 10
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your implementation is almost correct ๐Ÿ†—
Unfortunately, it returns negative numbers on negative inputs because of how mod works. Sometimes corner cases can be tricky to spot and fix...

Comment thread src/Chapter1.hs
Comment on lines +647 to +648
sumLast2 n = let last = mod n 10
seclast = mod (div n 10) 10 -- div n 10 gives the digit stripped off last digit.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is a wonderful solution! ๐Ÿ‘๐Ÿผ You correctly noticed that it is the div and mod, cool ๐Ÿ˜Ž

One hint to make your solution even shorter: you can see that you use both:

mod m 10
div m 10

The standard library has the divMod function, that actually combines inside both div and mod. And this is exactly what you use!.

So you could write it this way:

(x, y) = divMod m 10

You can see how we could pattern match on the pair ๐Ÿ™‚

Comment thread src/Chapter1.hs
firstDigit n = error "firstDigit: Not implemented!"

firstDigit :: Int -> Int
firstDigit n = if n < 10 then n else firstDigit (div n 10)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, that for a negative number like -19, this implementation will return the negative number itself instead of the last digit because the first check n < 10 will always succeed for negative numbers.

@vrom911 vrom911 added chapter1 hacktoberfest-accepted https://hacktoberfest.digitalocean.com/ labels Oct 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chapter1 hacktoberfest-accepted https://hacktoberfest.digitalocean.com/

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

โšก