Functional version of function

Is there a purely functional way of writing frequency(of:) in this code?


struct GenericDataFrequency<T: Hashable & Comparable> {
  var data: [T]
  var frequencies: [T : Int] {
    return Dictionary((data.map {($0, 1)}), uniquingKeysWith: {$0 + $1})
  }
  func frequency(of elements: [T]) -> [T : Int] {
    var collector = [T : Int]()
    for e in elements {
      collector[e] = frequencies[e] ?? 0
    }
    return collector
  }
}


I've been staring at it for ages and don't see it. This could be a valuable learning experience for me.

Accepted Reply

Wouldn't you know it: as soon as I posted my question, I thought of a solution:


  func frequency(of elements: Set<T>) -> [T : Int] {
    return Dictionary(uniqueKeysWithValues: elements.map {($0, frequencies[$0] ?? 0)})
  }


It seems to work.

Replies

Wouldn't you know it: as soon as I posted my question, I thought of a solution:


  func frequency(of elements: Set<T>) -> [T : Int] {
    return Dictionary(uniqueKeysWithValues: elements.map {($0, frequencies[$0] ?? 0)})
  }


It seems to work.