[英]List Recursion in Ocaml
這是我要達到的目的,並通過遞歸返回到一個值低於給定值的列表:
# list_below 3 [7; 1; 0; 3];;
- : int list = [1; 0]
# list_below 1 [-7; 1; 0; 3];;
- : int list = [-7; 0]
# list_below 9.0 [4.2; 3.6; 5.0; 12.8];;
- : float list = [4.2; 3.6; 5.0]
這是我到目前為止所寫的內容,似乎沒有返回任何內容。
let rec list_below thresh lst =
if List.hd lst > thresh then [] else
List.hd lst :: list_below thresh (List.tl lst);;
;;
您能告訴我我的代碼有什么問題嗎?
問題應該是傑弗里為您指出的。
您的問題表明您想實現list_below
,但是您的代碼顯示為list_above
。 我會在下面堅持到list_below
。
如果使用模式匹配,則可以非常直觀地實現Ocaml中的遞歸函數 。 例如,下面的代碼應該工作:
let rec list_below thresh lst =
match lst with
| [] -> []
| hd :: tl -> if hd < thresh then hd :: (list_below thresh tl)
else list_below thresh tl;;
如果第一個值高於閾值,則您的代碼始終返回一個空列表。 那是不對的。 一方面,它與您的第一個示例不一致。
您可以嘗試使用List.filter
。 由於要獲取小於提供的值的值列表,因此filter可以執行所需的操作。
這是過濾器的文檔:
val filter : ('a -> bool) -> 'a list -> 'a list
filter p l returns all the elements of the list l that satisfy the predicate p. The order of the elements in the input list is preserved.
您需要提供一個謂詞p。 謂詞是一個接受元素並返回布爾值的函數。 篩選器將使用此謂詞並將其應用於列表中的每個值。 如果謂詞對該元素返回true,則該元素將添加到結果列表中。
所以在你的情況下, list_below
應該是
let list_below thresh lst =
List.filter (fun elem -> elem < thresh) lst
列表中還有更多操作,請查看Real World OCaml中的本章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.