haskell: factors of a natural number -


I am trying to write a function in Haskell which excludes itself and calculates all the factors of a given number

The result should look like this:

  factorlist 15 = & gt; [1,3,5]  

I'm new to Haskell and the whole recap of the topic, I'm pretty sure I'm ready to apply in this example but I'm not

My idea is to compare the given number with the first element of the list with the div 2 with mod . Function but anyhow recursive and if the result is 0 , then I will add a number to a new list. (I hope this means understanding)

I appreciate any help on this matter

So far my code is: (This does not work .. But somehow to clarify my view)

  factorList :: int -> [Int] FactorList N | N`med` head [1.ddi2] == 0 = x: []  

There are several ways to handle this, but first of all, let us write a little helper:

  isFactorOf :: Integral A => A - & gt; A - & gt; In this way we can write  12 'isFactorOf' 24  and get either  true  Or  incorrect . For the recurring part, suppose we use a function with two arguments: one is the number that we want to make a difference, the second factor, which we are currently testing. We only accept  n & nbsp; `Div` & nbsp; 2  are testing equal or equal factors, and it goes beyond: 

  createList n f | F. & lt; = N` div` 2 = If F.FF is 'O' F then F: Next and Next | Otherwise = [] where next = createList n (f + 1)  

then if is a factor of the second parameter n Add it to the list and move on, otherwise we move forward. We only do this until f and lt; = N` div` 2 . Now to create factorial , we can use createList with enough second parameters:

  factorList n = createList n 1 < / Code> 

is recursive in the recurring createlist . As such, createList is one, and you can hide it in where inside factorial .

Note that with a easily defined factorList filter or list:

  factorList 'n = filter (`isFactorOf` n) [ 1 .. n` div` 2] factor '' N = [x | X & lt; - [1 .. n`div` 2], X` isFactorOf` n]  

But in this case you would not have written yourself a replay.

Further practice:

  • Try to apply the filter function manually.
  • Create another function, which is the only prime minister factor, you can either use your previous result and write a major filter or write a recursive function that will give them Generates directly (later gets faster)

Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -