简体   繁体   English

F#:声明 function 并在列表中查找元素

[英]F#: Declare function and find element in list

I'm quite new to F# and need some help with a problem.我对 F# 很陌生,需要一些帮助来解决问题。 I'm having trouble finding an element in a list: "Declare a function findRoute: Lid*LuggageCatalogue -> Route, that finds the route for a given luggage identification in a luggage catalogue"我无法在列表中找到一个元素:“声明一个 function findRoute:Lid*LuggageCatalogue -> Route,在行李目录中找到给定行李标识的路线”

I have listed the different types and given the types elements.我列出了不同的类型并给出了类型元素。

    type Lid = string 
    type Flight = string
    type Airport = string
    type Route = (Flight*Airport) list
    let route = [("DL 189","ATL"); ("DL 124","BRU"); ("SN 733","CPH"); ("SK 208","ATL"); ("DL 124","BRU"); ("SK 122","JFK")]

    type LuggageCatalogue = (Lid*Route) list
    let lc = [("DL 016-914", [("DL 189","ATL"); ("DL 124","BRU"); ("SN 733","CPH")]); 
    ("SK 222-142", [("SK 208","ATL"); ("DL 124","BRU"); ("SK 122","JFK")])]


    let findRoute fr = function
    match fr with
    | [] -> printf "No match"
    |

Where I'm stuck is that I cannot find the correct way to use the function to find the elements in the LuggageCatalogue list我卡住的地方是我找不到正确的方法来使用 function 在LuggageCatalogue列表中查找元素

Maybe you could start by filtering the luggage catalogue to better understand what is going on, eg也许您可以从过滤行李目录开始,以更好地了解发生了什么,例如

let filterlist lid = List.filter (fun (luggageid, _) -> luggageid = lid)

Then finding a particular item in the catalogue would be something like然后在目录中找到一个特定的项目就像

filterlist "SK 222-142" lc

Or even better, try to create the first part of the function yourself.或者更好的是,尝试自己创建 function 的第一部分。 Even though this is only the first step, maybe try to visualize how a recursive search function for a luggage id may look,即使这只是第一步,也可以尝试想象一下递归搜索 function 的行李 id 可能看起来如何,

let findfirst lid =
  let rec checktail lctail =
    match lctail with
    | [] -> invalidArg "lid" "luggageid not present in catalogue"
    | (id, r)::tail -> if id = lid then r else checktail tail
  checktail lc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM