Đang chuẩn bị liên kết để tải về tài liệu:
Foundations of F#.Net phần 3
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'foundations of f#.net phần 3', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 52 CHAPTER 3 FUNCTIONAL PROGRAMMING represent the end of a list. The Some constructor must contain a tuple. The first item in the tuple represents the value that will become the first value in the list. The second value in the tuple is the value that will be passed into the function the next time it is called. You can think of this value as an accumulator. The next example shows how this works. The identifier lazyList will contain three values. If the value passed into the function is less than 13 you append the list using this value to form the list element and then add 1 to the value passed to the list. This will be value passed to the function the next time it is called. If the value is greater than or equal to 13 you terminate the list by returning None. To display the list you use the function display a simple recursive function that processes the head of the list and then recursively processes the tail. light let lazyList LazyList.unfold fun x - if x 13 then Some x x 1 else None 10 let rec display l match l with LazyList.Cons h t - print_int h print_newline display t LazyList.Nil - display lazyList The results of this example when compiled and executed are as follows 10 11 12 Lazy lists are also useful to represent lists that don t terminate. A nonterminating list can t be represented by a classic list which is constrained by the amount of memory available. The next example demonstrates this by creating fibs an infinite list of all the Fibonacci numbers it uses the Seq module although it could just as well have used the LazyList module because the unfold function works in the same way in both. To display the results conveniently you use the function Seq.take to turn the first 20 items into an F list but you carry on calculating many more Fibonacci numbers as you use F bigint integers so you are limited by the size of a 32-bit integer. CHAPTER 3 FUNCTIONAL PROGRAMMING 53 light let fibs Seq.unfold fun n0 n1 - Some n0 n1 n0 n1 1I 1I let first20 Seq.take 20 fibs