.net-core - 比较两个字符串列表的函数

标签 .net-core f# c#-to-f#

我是 F# 的新手,我尝试完成这个任务:

制作一个函数比较:字符串列表 -> 字符串列表 -> 接受两个字符串列表并返回:-1、0 或 1 的 int

请帮忙。我花了很多时间,但我无法理解如何执行此任务。

最佳答案

根据任务,我假设您的教授希望通过此练习教您什么。我试着给你一个起点,而不是

  1. 让你感到困惑
  2. 提出“完成交易”的解决方案

我假设此任务的目标是使用递归函数和模式匹配来按元素比较它们的元素。它可能看起来有点像这里

open System

let aList = [ "Apple"; "Banana"; "Coconut" ]
let bList = [ "Apple"; "Banana"; "Coconut" ]
let cList = [ "Apple"; "Zebra" ]

let rec doSomething f (a : string list) (b : string list) =
    match (a, b) with
    | ([], []) ->
        printfn "Both are empty"
    | (x::xs, []) ->
        printfn "A has elements (we can unpack the first element as x and the rest as xs) and B is empty"
    | ([], x::xs) ->
        printfn "A is empty and B has elements (we can unpack the first element as x and the rest as xs)"
    | (x::xs, y::ys) ->
        f x y
        printfn "Both A and B have elements. We can unpack them as the first elements x and y and their respective tails xs and ys"
        doSomething f xs ys

let isItTheSame (a : string) (b : string) =
    if String.Equals(a, b) then
        printfn "%s is equals to %s" a b
    else
        printfn "%s is not equals to %s" a b

doSomething isItTheSame aList bList
doSomething isItTheSame aList cList

该示例具有三个不同的列表,其中两个相等,一个不同。 doSomething 函数接受一个函数 (string -> string -> unit) 和两个字符串列表。

在该函数中,您会看到模式匹配以及在最后一个匹配 block 中对 doSomething 的递归调用。签名并不完全是您所需要的,您可能想考虑如何在您不想停止递归的情况下更改参数化(最后一个匹配 block - 如果字符串相等,您希望继续比较,对吧?)。

只需获取代码并在 FSI 中试用即可。我相信,您会找到解决方案 🙂

关于.net-core - 比较两个字符串列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63925416/

相关文章:

c# - 新的 netstandardapp 和 netcoreapp TFM 之间有什么区别?

F#:Nullable<T> 支持

list - 获取 F# 中两个整数列表之间的匹配数

f# - 降低 API 流畅度的最佳方法?

f# - 接口(interface)方法和记录属性的 XML 文档

c# - F#:实现 "try cast"函数,参数化 "subtype of"约束不起作用

f# - 抽象元组函数中的参数名称

c# - 使用 Newtonsoft、dotnet core 2.2 与 dot net core 3.1 对 System.Version 进行序列化和反序列化

c# - Visual Studio 2019不会在项目打开时提取所需的Docker镜像

c# - 具有自定义 JWT 身份验证的 OAuth