Skip to content

Commit

Permalink
Merge pull request #2 from LucianoPAlmeida/cost-option
Browse files Browse the repository at this point in the history
Improvements on cost model API.
  • Loading branch information
LucianoPAlmeida authored Sep 7, 2021
2 parents dca5a30 + 4b10952 commit a5a9537
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
32 changes: 28 additions & 4 deletions Sources/strings/Levenshtein.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
//
//===----------------------------------------------------------------------===//

public struct LevenshteinCost {
public let insertion: Int
public let deletion: Int
public let substitution: Int
public struct LevenshteinCost: Equatable {
public var insertion: Int
public var deletion: Int
public var substitution: Int

public init(insertion: Int = 1, deletion: Int = 1, substitution: Int = 1) {
self.insertion = insertion
Expand All @@ -17,6 +17,30 @@ public struct LevenshteinCost {
}

public static var `default`: LevenshteinCost { LevenshteinCost() }

@inlinable
internal func _with(
_ property: WritableKeyPath<LevenshteinCost, Int>, value: Int
) -> LevenshteinCost {
var copy = self
copy[keyPath: property] = value
return copy
}

@inlinable
public func with(insertion: Int) -> LevenshteinCost {
return _with(\.insertion, value: insertion)
}

@inlinable
public func with(deletion: Int) -> LevenshteinCost {
return _with(\.deletion, value: deletion)
}

@inlinable
public func with(substitution: Int) -> LevenshteinCost {
return _with(\.substitution, value: substitution)
}
}

public struct Levenshtein<Source: StringProtocol> {
Expand Down
9 changes: 9 additions & 0 deletions Tests/stringsTests/LevenshteinTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ final class LevenshteinTests: XCTestCase {
XCTAssertEqual("friend".levenshteinDistance(to: "fried", cost: cost), 1)
XCTAssertEqual("test".levenshteinDistance(to: "team", cost: cost), 4)
}

func testLevenshteinCost() {
let cost = LevenshteinCost.default
let expected = LevenshteinCost(insertion: 3, deletion: 4, substitution: 5)

XCTAssertNotEqual(expected, cost)
XCTAssertEqual(expected, cost.with(deletion: 4).with(insertion: 3).with(substitution: 5))

}

static var allTests = [
("testLevenshteinDistances", testLevenshteinDistances),
Expand Down

0 comments on commit a5a9537

Please sign in to comment.