【问题标题】:A function that compare a two lists of string比较两个字符串列表的函数
【发布时间】:2020-09-16 17:47:40
【问题描述】:

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

创建一个函数 compare : string list -> string list -> int 接受两个字符串列表并返回:-1、0 或 1

请帮忙。我花了很多时间,我无法理解如何实现这个任务。

【问题讨论】:

  • 你有不同案例的例子吗?我不完全遵循您在这里想要实现的目标。另外:这绝不是学校/大学的编程练习,是吗? ??????
  • 是的,这是家庭作业中的练习之一。我不明白如何比较列表...我了解如何比较两个字符串或两个整数,但是如何比较两个字符串列表...
  • 也许你可以给一个提示或小例子如何开始?

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


【解决方案1】:

鉴于任务,我假设您的教授希望通过此练习教您什么。我会尽量给你一个没有的起点

  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) 和两个字符串列表。

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

只需获取代码并在 FSI 中试用即可。我有信心,你会找到解决方案?

【讨论】:

    【解决方案2】:

    在 F# 中,如果元素类型为,则许多集合是可比较的:

    let s1 = [ "a"; "b" ]
    let s2 = [ "foo"; "bar" ]
    
    compare s1 s2 // -5
    
    let f1 = [ (fun () -> 1); fun () -> 2 ]
    let f2 = [ (fun () -> 3); fun () -> 42 ]
    
    // compare f1 f2 (* error FS0001: The type '(unit -> int)' does not support the 'comparison' constraint. *)
    

    所以

    let slcomp (s1 : string list) s2 = compare s1 s2 |> sign
    

    作为原始问题的答案发布以供参考。

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多