Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function about even and odd numbers

I'm new to Haskell, started learning a couple of days ago and I have a question on a function I'm trying to make.

I want to make a function that verifies if x is a factor of n (ex: 375 has these factors: 1, 3, 5, 15, 25, 75, 125 and 375), then removes the 1 and then the number itself and finally verifies if the number of odd numbers in that list is equal to the number of even numbers!

I thought of making a functions like so to calculate the first part:

factor n = [x | x <- [1..n], n `mod`x == 0]

But if I put this on the prompt it will say Not in scope 'n'. The idea was to input a number like 375 so it would calculate the list. What I'm I doing wrong? I've seen functions being put in the prompt like this, in books.

Then to take the elements I spoke of I was thinking of doing tail and then init to the list. You think it's a good idea?

And finally I thought of making an if statement to verify the last part. For example, in Java, we'd make something like:

(x % 2 == 0)? even++ : odd++; // (I'm a beginner to Java as well)

and then if even = odd then it would say that all conditions were verified (we had a quantity of even numbers equal to the odd numbers)

But in Haskell, as variables are immutable, how would I do the something++ thing?

Thanks for any help you can give :)

like image 513
BVCGAAV Avatar asked Aug 31 '25 22:08

BVCGAAV


1 Answers

This small function does everything that you are trying to achieve:

f n = length evenFactors == length oddFactors
  where evenFactors = [x | x <- [2, 4..(n-1)], n `mod` x == 0]
        oddFactors  = [x | x <- [3, 5..(n-1)], n `mod` x == 0]
like image 55
11181 Avatar answered Sep 03 '25 20:09

11181