Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

recursion - 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.

question from:https://stackoverflow.com/questions/65853528/how-to-write-a-function-finding-even-numbers-in-list-on-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...