我是 F# 的新手,我尝试完成这个任务:
制作一个函数比较:字符串列表 -> 字符串列表 -> 接受两个字符串列表并返回:-1、0 或 1 的 int
请帮忙。我花了很多时间,但我无法理解如何执行此任务。
最佳答案
根据任务,我假设您的教授希望通过此练习教您什么。我试着给你一个起点,而不是
- 让你感到困惑
- 提出“完成交易”的解决方案
我假设此任务的目标是使用递归函数和模式匹配来按元素比较它们的元素。它可能看起来有点像这里
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/