Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - Python range 함수 구현 (2) INumber<T>를 이용한 개선

다음의 기능이 나왔으니,

.NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원
; https://www.sysnet.pe.kr/2/0/12785

이제 Python의 Range 함수를,

C# - Python range 함수 구현
; https://www.sysnet.pe.kr/2/0/11908

더 매끄럽게 구현할 수 있습니다. ^^ 이렇게!

public static IEnumerable<T> Range<T>(T start, T stop, T step = default) where T: INumber<T>
{            
    if (step == default)
    {
        step = T.One;
    }

    if (start < stop && step > T.Zero)
    {
        for (var i = start; i < stop; i += step)
        {
            yield return i;
        }
    }
    else if (start > stop && step < T.Zero)
    {
        for (var i = start; i > stop; i += step)
        {
            yield return i;
        }
    }
}

dynamic을 쓸 필요도 없고 unmanaged 제약으로 unsafe를 쓸 필요도 없어졌습니다. 당연히 출력 결과도 기존의 코드와 완전히 동일합니다. ^^

static void Main(string[] args)
{
    {
        var expected = Extension.RangePython<int>(1, 10, 1); // 기존 방식
        var results = Extension.Range(1, 10); // 새로운 방식
        foreach (var item in results.Zip(expected, (first, second) => Tuple.Create(first, second)))
        {
            Console.WriteLine($"{item.Item1} == {item.Item2}: {item.Item1 == item.Item2}");
        }
    }

    Console.WriteLine();

    {
        var expected = Extension.RangePython<double>(0.1, .13, 0.001); // 기존 방식
        var results = Extension.Range(0.1, .13, 0.001); // 새로운 방식
        foreach (var item in results.Zip(expected, (first, second) => Tuple.Create(first, second)))
        {
            Console.WriteLine($"{item.Item1} == {item.Item2}: {item.Item1 == item.Item2}");
        }
    }
}

/* 출력 결과
1 == 1: True
2 == 2: True
3 == 3: True
4 == 4: True
5 == 5: True
6 == 6: True
7 == 7: True
8 == 8: True
9 == 9: True

0.1 == 0.1: True
0.101 == 0.101: True
0.10200000000000001 == 0.10200000000000001: True
0.10300000000000001 == 0.10300000000000001: True
0.10400000000000001 == 0.10400000000000001: True
0.10500000000000001 == 0.10500000000000001: True
0.10600000000000001 == 0.10600000000000001: True
0.10700000000000001 == 0.10700000000000001: True
0.10800000000000001 == 0.10800000000000001: True
0.10900000000000001 == 0.10900000000000001: True
0.11000000000000001 == 0.11000000000000001: True
0.11100000000000002 == 0.11100000000000002: True
0.11200000000000002 == 0.11200000000000002: True
0.11300000000000002 == 0.11300000000000002: True
0.11400000000000002 == 0.11400000000000002: True
0.11500000000000002 == 0.11500000000000002: True
0.11600000000000002 == 0.11600000000000002: True
0.11700000000000002 == 0.11700000000000002: True
0.11800000000000002 == 0.11800000000000002: True
0.11900000000000002 == 0.11900000000000002: True
0.12000000000000002 == 0.12000000000000002: True
0.12100000000000002 == 0.12100000000000002: True
0.12200000000000003 == 0.12200000000000003: True
0.12300000000000003 == 0.12300000000000003: True
0.12400000000000003 == 0.12400000000000003: True
0.12500000000000003 == 0.12500000000000003: True
0.12600000000000003 == 0.12600000000000003: True
0.12700000000000003 == 0.12700000000000003: True
0.12800000000000003 == 0.12800000000000003: True
0.12900000000000003 == 0.12900000000000003: True

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




그런데, 한 가지 아쉬운 것이 있군요. ^^

public static IEnumerable<T> Range<T>(T start, T stop, T step = default) where T: INumber<T>
{        
    if (step == default)
    {
        step = T.One;
    }
    
    // ...[생략]...
}

위의 코드에서 T step의 기본값을 default로 주었는데, 원래는 다음과 같이 설정할 수 있었으면 더 좋았을 것입니다.

public static IEnumerable<T> Range<T>(T start, T stop, T step = T.One) where T: INumber<T>

하지만, 메서드 선언에서의 문맥 단계에서는 T에 대한 풀이를 아직 제공하지 않는 것인지(혹은 못하는 것인지) 현재는 다음과 같은 컴파일 오류가 발생합니다.

error CS0103: The name 'T' does not exist in the current context

이것만 더해진다면 완벽하지 않을까... 싶군요. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/18/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-09-07 11시00분
System.Range를 이용한 구현 방법을 소개하는데,

[C#] foreach에 Range 사용하기
; https://forum.dotnetdev.kr/t/c-foreach-range/1630

Making «foreach» loop as fast as «for» loop
; https://habr.com/en/post/575916/

표현이 더 간결해서 마음에 듭니다. ^^

foreach (var i in 1..1000)
{
    Console.WriteLine(i);
}

static class RangeExtension
{
    public static IEnumerator<int> GetEnumerator(this Range @this)
    {
        for (var i = @this.Start.Value; i < @this.End.Value; i++)
        {
            yield return i;
        }
    }
}
정성태

... 106  [107]  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11250정성태7/13/201720805디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201718630오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201725101오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
11247정성태7/12/201719480오류 유형: 408. SqlConnection 객체 생성 시 무한 대기 문제파일 다운로드1
11246정성태7/11/201718194VS.NET IDE: 118. Visual Studio - 다중 폴더에 포함된 파일들에 대한 "Copy to Output Directory"를 한 번에 설정하는 방법
11245정성태7/10/201723788개발 환경 구성: 321. Visual Studio Emulator for Android 소개 [2]
11244정성태7/10/201723363오류 유형: 407. Visual Studio에서 ASP.NET Core 실행할 때 dotnet.exe 프로세스의 -532462766 오류 발생 [1]
11243정성태7/10/201720064.NET Framework: 666. dotnet.exe - 윈도우 운영체제에서의 .NET Core 버전 찾기 규칙
11242정성태7/8/201720303제니퍼 .NET: 27. 제니퍼 닷넷 적용 사례 (7) - 노후된 스토리지 장비로 인한 웹 서비스 Hang (멈춤) 현상
11241정성태7/8/201719039오류 유형: 406. Xamarin 빌드 에러 XA5209, APT0000
11240정성태7/7/201721974.NET Framework: 665. ClickOnce를 웹 브라우저를 이용하지 않고 쿼리 문자열을 전달하면서 실행하는 방법 [3]파일 다운로드1
11239정성태7/6/201723497.NET Framework: 664. Protocol Handler - 웹 브라우저에서 데스크톱 응용 프로그램을 실행하는 방법 [5]파일 다운로드1
11238정성태7/6/201720993오류 유형: 405. NT 서비스 시작 시 "Error 1067: The process terminated unexpectedly." 오류 발생 [2]
11237정성태7/5/201722630.NET Framework: 663. C# - PDB 파일 경로를 PE 파일로부터 얻는 방법파일 다운로드1
11236정성태7/4/201725925.NET Framework: 662. C# - VHD/VHDX 가상 디스크를 마운트하지 않고 파일을 복사하는 방법파일 다운로드1
11235정성태6/29/201720095Math: 20. Matlab/Octave로 Gram-Schmidt 정규 직교 집합 구하는 방법
11234정성태6/29/201717409오류 유형: 404. SharePoint 2013 설치 과정에서 "The username is invalid The account must be a valid domain account" 오류 발생
11233정성태6/28/201717296오류 유형: 403. SharePoint Server 2013을 Windows Server 2016에 설치할 때 .NET 4.5 설치 오류 발생
11232정성태6/28/201718257Windows: 144. Windows Server 2016에 Windows Identity Extensions을 설치하는 방법
11231정성태6/28/201718901디버깅 기술: 86. windbg의 mscordacwks DLL 로드 문제 - 세 번째 이야기 [1]
11230정성태6/28/201718062제니퍼 .NET: 26. 제니퍼 닷넷 적용 사례 (6) - 잦은 Recycle 문제
11229정성태6/27/201719308오류 유형: 402. Windows Server Backup 관리 콘솔이 없어진 경우
11228정성태6/26/201716767개발 환경 구성: 320. Visual Basic .NET 프로젝트에서 내장 Manifest 자원을 EXE 파일로부터 제거하는 방법파일 다운로드1
11227정성태6/19/201724574개발 환경 구성: 319. windbg에서 python 스크립트 실행하는 방법 - pykd [6]
11226정성태6/19/201716372오류 유형: 401. Microsoft Edge를 실행했는데 입력 반응이 없는 경우
11225정성태6/19/201715733오류 유형: 400. Outlook - The required file ExSec32.dll cannot be found in your path. Install Microsoft Outlook again.
... 106  [107]  108  109  110  111  112  113  114  115  116  117  118  119  120  ...