Functional implementation of learning algorithm (still occasional bug)