Chris
Chris

Reputation: 31266

How to implement Python class in F#

I have the following simple class implementation in Python. I would like to duplicate the functionality in F#...but I am not sure how...

class MyClass(object):

    def __init__(self):
        pass

    def addEvidence(self,dataX,dataY):

        newdataX = np.ones([dataX.shape[0],dataX.shape[1]+1])
        newdataX[:,0:dataX.shape[1]]=dataX

        # build and save the model
        self.model_coefs, residuals, rank, s = np.linalg.lstsq(newdataX, dataY)

    def query(self,points):

        return (self.model_coefs[:-1] * points).sum(axis = 1) + self.model_coefs[-1]

So, in pseudo-code, the class looks like this:

Class()

    self.model_coefs = []
    self.residuals = []
    self.rank = 0

    self.addEvidence(dataX,dataY):

         x, y, z = f(dataX,dataY)

         self.model_coefs <- x
         self.residuals <- y
         self.rank <- z

    self.query(points)

         return ([self.model_coefs[i] * points[i] for i in points].sum()) + self.model_coefs[self.model_coefs.length]

And if there is an F-sharpy way to do this, great--The thing is, the entity is kind of a data-bin with a functional wrapper by design, so I'm not sure how it would be done with functions...

Anyhow, here is my try so far (I'm skipping the linear regression for now..)

namespace Learners

type LinearRegressionLearner() = 
    member this.ModelCoefficients  : int [] = [|0;0|]
    member this.Residuals : int[] = [||]
    member this.Rank = 0

    member this.addEvidence dataX dataY = "expletive"
    member this.query (points:int[]) = 
           points |> Array.iteri(fun i x -> x * this.ModelCoefficients.[i])

I get an error here: points |> Array.iteri(fun i x -> x * this.ModelCoefficients.[i])...I guess this.ModelCoefficients.[i] is a unit and doesn't match x, which is an integer??

Upvotes: 2

Views: 148

Answers (1)

ildjarn
ildjarn

Reputation: 62995

Array.iteri (as with all iter functions) expects a function that returns unit – yours returns int. Maybe you want Array.mapi instead?

Upvotes: 3

Related Questions