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;
        }
    }
}
정성태

1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13531정성태1/16/20242062닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242035닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241915닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242061Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242011오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242108닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242061오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242112오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241930오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242091닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242153닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241887오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241983닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242249닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242099스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242182닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242461닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242107개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242035닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20241997개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242018닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241953닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241971오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242028오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242716닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232202닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...