Skip to content

Commit 8afb5f2

Browse files
committed
4.2 Data Types (string concatentation)
1 parent f9e6f14 commit 8afb5f2

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

evaluator/evaluator.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,8 @@ func evalInfixExpression(
249249
// The check for integer operands has to be higher up in the switch
250250
// statement.
251251
return evalIntegerInfixExpression(operator, left, right)
252+
case left.Type() == object.STRING_OBJ && right.Type() == object.STRING_OBJ:
253+
return evalStringInfixExpression(operator, left, right)
252254
case operator == "==":
253255
// Using pointer comparison to check for equality between booleans.
254256
return nativeBoolToBooleanObject(left == right)
@@ -294,6 +296,23 @@ func evalIntegerInfixExpression(
294296
}
295297
}
296298

299+
func evalStringInfixExpression(
300+
operator string,
301+
left, right object.Object,
302+
) object.Object {
303+
// Check for the correct operator.
304+
if operator != "+" {
305+
return newError("unknown operator: %s %s %s",
306+
left.Type(), operator, right.Type())
307+
}
308+
309+
// Unwrap the string objects and construct a new string that's a
310+
// concatenation of both operands.
311+
leftVal := left.(*object.String).Value
312+
rightVal := right.(*object.String).Value
313+
return &object.String{Value: leftVal + rightVal}
314+
}
315+
297316
func evalIfExpression(
298317
ie *ast.IfExpression,
299318
env *object.Environment,

evaluator/evaluator_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,10 @@ func TestErrorHandling(t *testing.T) {
206206
"5; true + false; 5",
207207
"unknown operator: BOOLEAN + BOOLEAN",
208208
},
209+
{
210+
`"Hello" - "World"`,
211+
"unknown operator: STRING - STRING",
212+
},
209213
{
210214
"if (10 > 1) { true + false; }",
211215
"unknown operator: BOOLEAN + BOOLEAN",
@@ -345,6 +349,20 @@ func TestStringLiteral(t *testing.T) {
345349
}
346350
}
347351

352+
func TestStringConcatenation(t *testing.T) {
353+
input := `"Hello" + " " + "World!"`
354+
355+
evaluated := testEval(input)
356+
str, ok := evaluated.(*object.String)
357+
if !ok {
358+
t.Fatalf("object is not String. got=%T (%+v)", evaluated, evaluated)
359+
}
360+
361+
if str.Value != "Hello World!" {
362+
t.Errorf("String has wrong value. got=%q", str.Value)
363+
}
364+
}
365+
348366
func testEval(input string) object.Object {
349367
l := lexer.New(input)
350368
p := parser.New(l)

0 commit comments

Comments
 (0)