반복 가능한 객체와 지연 평가
Coddy의 C# 개발자를 위한 Dart 코스 레슨. 48개 중 18번째.
C# LINQ IEnumerable 파이프라인과 Dart Iterable은 모두 지연 실행될 수 있으며 다시 순회할 수 있습니다. C#에서는 ToList가 구체화하고, Dart에서는 toList가 그렇게 합니다. 반복해서 순회하면 콜백의 부수 효과가 반복될 수 있습니다.
Dart의 map과 where는 지연 Iterable을 반환합니다. 요소가 요청될 때 콜백이 실행되며, 나중에 다시 순회하면 콜백이 반복 실행될 수 있습니다. 구체적인 스냅샷이 필요할 때 toList로 결과를 구체화합니다.
완전한 C# 프로그램:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main(){var result=new[]{2,3}.Select(n=>{Console.WriteLine("visit:"+n);return n*2;});Console.WriteLine("made");Console.WriteLine(result.First());}
}
완전한 Dart 프로그램:
void main(){final result=[2,3].map((n){print('visit:$n');return n*2;});print('made');print(result.first);}챌린지
쉬움excess(List<int> values,int floor)를 구현하세요. floor보다 큰 값만 선택하고, floor를 빼고, 순서를 유지한 뒤 새 리스트를 반환하세요. 입력은 floor 뒤에 값들이 이어지며, 모두 -100에서 100 사이입니다. 출력은 쉼표로 구분된 결과 또는 empty입니다.
편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart가 입력을 파싱하고 출력을 반환합니다. 잠긴 드라이버는 공개 API를 별도로 테스트하고 결과를 줄바꿈 하나와 함께 출력합니다.
코드는 functions.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(excess([3,7,4],3).join(',')=='4,1');
stdout.writeln(solve(input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러