support non-nil empty list
All checks were successful
Go / test (push) Successful in 2s

This commit is contained in:
Adam Jeniski 2025-11-04 11:50:38 -10:00
parent f636603fd2
commit d3997bfb53
2 changed files with 48 additions and 1 deletions

View File

@ -5,11 +5,17 @@ import (
"strings" "strings"
) )
type EmptyList struct{}
type List struct { type List struct {
Value any Value any
next *List next *List
} }
func Empty() *EmptyList {
return new(EmptyList)
}
func New(val any) *List { func New(val any) *List {
return new(List).Init(val) return new(List).Init(val)
} }
@ -28,6 +34,10 @@ func (this *List) Conj(val any) *List {
return Conj(this, val) return Conj(this, val)
} }
func (this *EmptyList) Conj(val any) *List {
return Conj(nil, val)
}
func Conj(this *List, val any) *List { func Conj(this *List, val any) *List {
if this == nil { if this == nil {
return New(val) return New(val)
@ -59,13 +69,25 @@ func (this *List) First() any {
return First(this) return First(this)
} }
func (this *EmptyList) First() any {
return First(nil)
}
func IsEmpty(this *List) bool { func IsEmpty(this *List) bool {
return this == nil return this == nil
} }
func (this *List) IsEmpty() bool {
return this == nil
}
func (this *EmptyList) IsEmpty() bool {
return true
}
func String(this *List) string { func String(this *List) string {
if this == nil { if this == nil {
return "{}" return "()"
} }
var sb strings.Builder var sb strings.Builder
sb.WriteRune('(') sb.WriteRune('(')

25
list/list_test.go Normal file
View File

@ -0,0 +1,25 @@
package list
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestReadConj(t *testing.T) {
l := Empty().Conj(5).Conj(6).Conj(7)
assert.Equal(t, "(7 6 5)", l.String(), "should insert at head")
}
func TestReadFirst(t *testing.T) {
l := Empty().Conj(5).Conj(6).Conj(7)
assert.Equal(t, 7, l.First(), "should return first element")
assert.Equal(t, nil, Empty().First(), "should return nil")
assert.Equal(t, 5, New(5).First(), "should get first from New")
}
func TestReadRest(t *testing.T) {
l := Empty().Conj(5).Conj(6).Conj(7)
assert.Equal(t, "(6 5)", l.Rest().String(), "should return rest sublist")
assert.Equal(t, "(5)", l.Rest().Rest().String(), "should return rest sublist")
assert.Equal(t, "()", l.Rest().Rest().Rest().String(), "should return rest sublist")
}