Skip to content

Commit

Permalink
Added a FlatTypes() method for easier access for some logic-related work
Browse files Browse the repository at this point in the history
  • Loading branch information
chewxy committed Apr 9, 2017
1 parent 6e688e1 commit 8c3004b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
23 changes: 23 additions & 0 deletions functionType.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,26 @@ func (t *FunctionType) Ret(recursive bool) Type {

return t.b
}

// FlatTypes returns the types in FunctionTypes as a flat slice of types. This allows for easier iteration in some applications
func (t *FunctionType) FlatTypes() Types {
retVal := BorrowTypes(8) // start with 8. Can always grow
retVal = retVal[:0]

if a, ok := t.a.(*FunctionType); ok {
ft := a.FlatTypes()
retVal = append(retVal, ft...)
ReturnTypes(ft)
} else {
retVal = append(retVal, t.a)
}

if b, ok := t.b.(*FunctionType); ok {
ft := b.FlatTypes()
retVal = append(retVal, ft...)
ReturnTypes(ft)
} else {
retVal = append(retVal, t.b)
}
return retVal
}
12 changes: 12 additions & 0 deletions functionType_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,15 @@ var fnApplyTests = []struct {
// (a -> b) -> c
{NewFnType(NewFnType(TypeVariable('a'), TypeVariable('b')), TypeVariable('a')), mSubs{'a': proton, 'b': neutron}, NewFnType(NewFnType(proton, neutron), proton)},
}

func TestFunctionType_FlatTypes(t *testing.T) {
fnType := NewFnType(TypeVariable('a'), TypeVariable('b'), TypeVariable('c'))
ts := fnType.FlatTypes()
correct := Types{TypeVariable('a'), TypeVariable('b'), TypeVariable('c')}
assert.Equal(t, ts, correct)

fnType2 := NewFnType(fnType, TypeVariable('d'))
correct = append(correct, TypeVariable('d'))
ts = fnType2.FlatTypes()
assert.Equal(t, ts, correct)
}

0 comments on commit 8c3004b

Please sign in to comment.