DEV Community

Shashwat Seth
Shashwat Seth

Posted on

2

Please help me with this haskell program.

Define a function dropOdds :: Int -> Int with the following behaviour. For any positive number m, dropOdds m is got by dropping all the odd digits in m. (If all the digits in the number are odd, the answer should be 0.)
Test cases:
dropOdds 0 = 0
dropOdds 8 = 8
dropOdds 1357 = 0

Top comments (8)

Collapse
 
totally_chase profile image
Phantz

Ok, I won't give you the answer directly since that'd be harmful to your learning. I'll ask 3 questions instead - try to answer them:-

  • How can you turn a number into a list of "digits".
  • How can you check if a "digit" is odd?
  • How do you "drop" certain elements of a list that match a criteria? (hint: filter)

You'll notice the quotes I put around the word "digits". I generally prefer using Char for "digits". But one may just as well use Int. Whichever you use, your answers will depend on it.

Collapse
 
benjioe profile image
Benjioe • Edited

You can use recursion too :

  • How can you check if a "digit" is odd?
  • How can you apply a function only on first digit?
  • How can you apply that function on each other digits?
Collapse
 
shashwatseth profile image
Shashwat Seth

Thanks man

Collapse
 
shashwatseth profile image
Shashwat Seth

Thankyou so much, I got it right!!!!!

Collapse
 
benjioe profile image
Benjioe

...

Collapse
 
shashwatseth profile image
Shashwat Seth

I'm new to haskell. I want the solution for this so that I can understand the concepts

Collapse
 
gopinathvarad profile image
gopinathvarad

even I want this answer !!

Collapse
 
benjioe profile image
Benjioe

With Recursion :

dropOdds :: Int -> Int
dropOdds x
    | x >= 10 = 10 * dropOdds restDigits + filterDrops firstDigit
    | otherwise = filterDrops x
    where 
      firstDigit = x `mod` 10
      restDigits = x `div` 10


filterDrops x 
    | x `mod` 2 == 0 = x -- x is even => we keep it
    | otherwise = 0 -- x is drop => we 


main =  do
   print(dropOdds 0)
   print(dropOdds 8)
   print(dropOdds 10)
   print(dropOdds 1357)
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay