问题描述
我是F#的新手,我尝试执行此任务:
进行功能比较:字符串列表->字符串列表-> int,它接受两个字符串列表并返回:-1、0或1
请帮助。我花了很多时间,但我不明白如何执行此任务。
解决方法
鉴于任务,我假设您的教授希望通过本练习教您什么。我会尽力为您提供一个起点
- 使您困惑
- 提出“完成交易”解决方案
我假设此任务的目标是使用递归函数和模式匹配来逐元素比较它们的元素。这里看起来像这样
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中试用即可。我有信心,您会找到解决方法的?
,在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
发布了供参考,因为已经回答了原始问题。