简体   繁体   中英

How to write a function finding even numbers in list on F#

Hello guys so i have a problem about finding even numbers in the list. Im so new in F# and i need to find even numbers in the list with function.

I have the real question:

//Given is a list of integers. Write a recursive function that returns a pair of lists: a list of even numbers //and a list of numbers divisible by three. For example, for the list [1; 2; 3; 4; 5; 6] we should get ([2; 4; 6], [3; 6]).

I tried this:

let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
let evens list1 =
   let isEven x = x % 2 = 0  
                              
   List.filter isEven list1  
                              

But its not working. Thank you for your help.

What you've got is correct for finding even numbers. The only thing missing is that you need to call your evens function, passing it list1 , like this: evens list1 .

Keep in mind that the parameters of a function are different from its arguments. In this case, you've called both the parameter and the argument list1 , which may be confusing you.

Here's a complete version, using two different names for clarity:

let myList = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
let evens anyList =
   let isEven x = x % 2 = 0  
   List.filter isEven anyList
printfn "%A" (evens myList)

Once you understand how this works, you can try solving the full problem you mentioned.

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