【问题标题】:F#: Declare function and find element in listF#:声明函数并在列表中查找元素
【发布时间】:2020-01-28 15:17:50
【问题描述】:

我对 F# 很陌生,需要一些帮助来解决问题。我无法在列表中找到一个元素: "声明一个函数 findRoute: Lid*LuggageCatalogue -> Route,在行李目录中查找给定行李标识的路线"

我列出了不同的类型并给出了类型元素。

    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"
    |

我卡住的地方是我找不到使用该函数在LuggageCatalogue 列表中查找元素的正确方法

【问题讨论】:

  • 问题似乎是你还没有真正写过任何代码。您应该尝试这样做并返回更具体的问题,例如编译器错误或它没有产生您期望的结果。
  • 请不要删除问题的重要部分。如果您在绕过一些反抄袭或反作弊工具时遇到问题,那么您真的应该在采取行动之前考虑到这一点。

标签: math functional-programming f# computer-science f#-interactive


【解决方案1】:

也许您可以从过滤行李目录开始,以更好地了解发生了什么,例如

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

然后在目录中查找特定项目将类似于

filterlist "SK 222-142" lc

或者更好的是,尝试自己创建函数的第一部分。即使这只是第一步,也可以尝试想象一下用于行李 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

【讨论】:

  • 非常感谢您的回答!接下来的几项任务真的让我大开眼界。你介意解释一下参数中“r”的使用吗?
  • @B.O.C.当然。这是更好的 F# 功能之一 - 模式匹配。如果您编写此代码let (id, r)::tail = lc,则来自lc 的数据将分成几个“片段”。在这种情况下,id 将是字符串“DL 016-914”,r 将成为字符串列表 [("DL 189", "ATL"); (“DL 124”、“BRU”); ("SN 733", "CPH")] 和 tail 将是 lc 行李目录的其余部分,其中目录(列表)的第一个“项目”被丢弃。
猜你喜欢
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 2015-09-06
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多