0

I am new to GO and I am using golang to write a simple type interface. The type is defined as:

type Sequence []float64

and the interface is:

type Stats interface {

        greaterThan(x float64) Sequence
}

The function greaterThan(x float64) should return a new Sequence that is the same as the numbers in the object // except all numbers less than, or equal to, x have been removed.

Here is my try, but it will not compile. I don't know how to fix it. My question is : how can I delete an item from structure type? Should I use a map? (as my try)

package main

import "fmt"

type Sequence []float64

type Stats interface {

        greaterThan(x float64) Sequence
}

func (s Sequence) greaterThan(x float64) Sequence{

    var i int
    var f float64
    set := make(map[float64]int)
    var v = f[i] Sequence

    for i, f := range set{

    for j := 0; j <= len(s); j++ {
        if s[j] <= x {
        delete(set, s[j])
        }
    }
}

    return v
}

func display(s Sequence) {

        fmt.Println("s.greaterThan(2):", s.greaterThan(2))

}

func main() {

        s := Sequence([]float64{1, 2, 3, -1, 6, 3, 2, 1, 0})
        display(s)

}
2
  • What error messages does the compilation attempt show you? Commented Feb 4, 2014 at 12:18
  • BTW. as seen here delete takes the map (in your case set), and the key (in your case j) as arguments. So the delete call would look like delete(set, i) not delete(set, s[j]) Commented Feb 4, 2014 at 12:22

1 Answer 1

4

I'd do it like this:

package main
import "fmt"
type Sequence []float64
type Stats interface {
    greaterThan(x float64) Sequence
}

func (s Sequence) greaterThan(x float64) (ans Sequence) {
    for _, v := range s {
        if v > x {
            ans = append(ans, v)
        }
    }
    return ans
}

func main() {
    s := Sequence{1, 2, 3, -1, 6, 3, 2, 1, 0}
    fmt.Printf("%v\n", s.greaterThan(2))
}

See http://play.golang.org/p/qXi5uE-25v

Most probably you should not delete items from the slice but construct a new one containing only the wanted ones.

Just out of curiosity: What do you want to do with the interface Stat?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.