%install '.package(path: "$cwd/FastaiNotebook_08_data_block")' FastaiNotebook_08_data_block
Installing packages: .package(path: "/home/ubuntu/fastai_docs/dev_swift/FastaiNotebook_08_data_block") FastaiNotebook_08_data_block With SwiftPM flags: [] Working in: /tmp/tmpd4g5mfxf Fetching https://github.com/mxcl/Path.swift Fetching https://github.com/JustHTTP/Just Completed resolution in 3.88s Cloning https://github.com/mxcl/Path.swift Resolving https://github.com/mxcl/Path.swift at 0.16.2 Cloning https://github.com/JustHTTP/Just Resolving https://github.com/JustHTTP/Just at 0.7.1 Compile Swift Module 'Just' (1 sources) Compile Swift Module 'Path' (9 sources) Compile Swift Module 'FastaiNotebook_08_data_block' (13 sources) Compile Swift Module 'jupyterInstalledPackages' (1 sources) Linking ./.build/x86_64-unknown-linux/debug/libjupyterInstalledPackages.so Initializing Swift... Loading library... Installation complete!
// export
public protocol HetDictKey: Hashable {
associatedtype ValueType
static var defaultValue: ValueType { get }
}
// export
public struct HeterogeneousDictionary {
private var underlying: [AnyHashable : Any] = [:]
public init() {}
public init<T: HetDictKey>(_ key: T, _ value: T.ValueType) {
self.underlying = [key: value]
}
public init<T1: HetDictKey, T2: HetDictKey>(_ key1: T1, _ value1: T1.ValueType, _ key2: T2, _ value2: T2.ValueType) {
self.underlying = [key1: value1, key2: value2]
}
public subscript<T: HetDictKey>(key: T) -> T.ValueType {
get {
return underlying[key] as! T.ValueType? ?? T.defaultValue
}
set(newValue) {
underlying[key] = newValue as Any
}
}
public mutating func merge(_ other: HeterogeneousDictionary,
uniquingKeysWith combine: (Any, Any) throws -> Any) rethrows {
try self.underlying.merge(other.underlying, uniquingKeysWith: combine)
}
}
// export
// Common keys
public struct Accuracy: HetDictKey, Equatable {
public init() {}
public static var defaultValue: Float = 0
}
public struct LearningRate: HetDictKey, Equatable {
public init() {}
public static var defaultValue: Float = 0.4
}
public struct StepCount: HetDictKey, Equatable {
public init() {}
public static var defaultValue = 0
}
// Sample usage
var m = HeterogeneousDictionary()
print(m[LearningRate()])
m[LearningRate()] = 3.4
print(m[LearningRate()])
print(m[StepCount()])
m[StepCount()] = 3
print(m[StepCount()])
0.4 3.4 0 3
print(type(of: m[StepCount()]))
print(type(of: m[LearningRate()]))
Int Float
Note: for performance, need to optimize hashcode to avoid collisions.
import Path
import FastaiNotebook_08_data_block
notebookToScript(fname: (Path.cwd / "08a_heterogeneous_dictionary.ipynb").string)