Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)

.NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원

(2022-07-15 업데이트) 이 기능은 C# 11에 포함될 예정이고, .NET 7 환경을 필요로 합니다.



.NET 6에 다음과 같은 기능이 추가되었다고 합니다.

Preview Features in .NET 6 – Generic Math
; https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/

이 기능에 대한 요청은 오래전부터 있었다는데, 아마도 근래의 딥러닝으로 인한 수학 라이브러리가 점점 더 중요성이 대두되면서 더 이상 버틸 수 없어 내놓게 된 것이 아닌가... 예상이 되는데요. ^^

이에 대한 의미를 느끼기 위해 간단하게 예를 하나 들어볼까요? ^^

가령, 여러분들이 다음과 같이 List를 생성했을 때, 이에 대한 합계를 구하는 코드를 제네릭 메서드로 만들고 싶다고 가정해 보겠습니다.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>();
        list.AddRange(new[] { 1, 2, 3 });

        Console.WriteLine(list.합계());
    }
}

public static class MyLinqExtension
{
    public static T 합계<T>(this IEnumerable<T> arg)
    {
        T sum = default;

        foreach (T item in arg)
        {
            sum = sum + item; // 컴파일 오류
        }

        return sum;
    }
}

아쉽게도 위의 코드는 "sum = sum + item" 코드에서 다음과 같은 컴파일 오류가 발생합니다.

error CS0019: Operator '+' cannot be applied to operands of type 'T' and 'T'

왜냐하면, 해당 T 타입은 더하기 연산을 지원하는 타입이 아닐 수도 있기 때문입니다. 즉, .NET 5 이전까지는 T 인스턴스가 숫자형 타입이라고 강제할 수 있는 어떠한 방법도 제공되지 않았습니다.




아니, 그렇다면 기존의 IEnumerable<T>에 있던 Sum은 뭡니까?

List<int> list = new List<int>();
list.AddRange(new[] { 1, 2, 3 });

Console.WriteLine(list.Sum());

사실 위의 코드 이면에는 마이크로소프트의 눈물겨운 노력이 있었습니다. 즉, 위의 코드를 가능하게 하도록 각각의 숫자형 타입마다 동일한 이름의 확장 메서드를 제공하는 방식으로 구현을 했었습니다.

public static class Enumerable
{
    public static int Sum(this IEnumerable<int> source);
    public static int? Sum(this IEnumerable<int?> source);
    public static long Sum(this IEnumerable<long> source);
    public static long? Sum(this IEnumerable<long?> source);
    public static float Sum(this IEnumerable<float> source);
    public static float? Sum(this IEnumerable<float?> source);
    public static double Sum(this IEnumerable<double> source);
    public static double? Sum(this IEnumerable<double?> source);
    public static decimal Sum(this IEnumerable<decimal> source);
    public static decimal? Sum(this IEnumerable<decimal?> source);
}

심지어 selector를 인자로 받는 또 다른 Sum 메서드까지 합치면,

public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
public static int? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector)
public static long Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector)
public static long? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector)
public static float Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector)
public static float? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector)
public static double Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector)
public static double? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector)
public static decimal Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector)
public static decimal? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)

기능 하나당 10개의 메서드를 지겹게 구현했던 것입니다. 바로 이러한 중복 문제를, .NET 6에 새롭게 추가된 인터페이스들로 인해 해결할 수 있습니다.

Operator Interface Name Summary
IParseable Parse(string, IFormatProvider)
ISpanParseable Parse(ReadOnlySpan<char>, IFormatProvider)
IAdditionOperators x + y
IBitwiseOperators x & y, x | y, x ^ y, and ~x
IComparisonOperators x < y, x > y, x <= y, and x >= y
IDecrementOperators --x and x--
IDivisionOperators x / y
IEqualityOperators x == y and x != y
IIncrementOperators ++x and x++
IModulusOperators x % y
IMultiplyOperators x * y
IShiftOperators x << y and x >> y
ISubtractionOperators x - y
IUnaryNegationOperators -x
IUnaryPlusOperators +x
IAdditiveIdentity (x + T.AdditiveIdentity) == x
IMinMaxValue T.MinValue and T.MaxValue
IMultiplicativeIdentity (x * T.MultiplicativeIdentity) == x
IBinaryFloatingPoint Members common to binary floating-point types
IBinaryInteger Members common to binary integer types
IBinaryNumber Members common to binary number types
IFloatingPoint Members common to floating-point types
INumber Members common to number types
ISignedNumber Members common to signed number types
IUnsignedNumber Members common to unsigned number types

결국, .NET 6에선 기존 숫자형 타입들에 대해 위에서 정의한 인터페이스를 반영했는데요, 일례로 Int32는 다음과 같이 바뀐 것을 볼 수 있습니다.

public readonly struct Int32 : IComparable, IComparable<int>, IConvertible, IEquatable<int>,
    ISpanFormattable, IFormattable, IBinaryInteger<int>, IBinaryNumber<int>, 
    IBitwiseOperators<int, int, int>, INumber<int>, 
    IAdditionOperators<int, int, int>, IAdditiveIdentity<int, int>, 
    IComparisonOperators<int, int>, IEqualityOperators<int, int>, 
    IDecrementOperators<int>, IDivisionOperators<int, int, int>, 
    IIncrementOperators<int>, IModulusOperators<int, int, int>, 
    IMultiplicativeIdentity<int, int>, IMultiplyOperators<int, int, int>, 
    IParseable<int>, ISpanParseable<int>, ISubtractionOperators<int, int, int>, 
    IUnaryNegationOperators<int, int>, IUnaryPlusOperators<int, int>,
    IShiftOperators<int, int>, IMinMaxValue<int>, ISignedNumber<int>
{
    //...
}

따라서 이제 처음에 우리가 만들었던 "합계" 메서드도 다음과 같이 간단하게 구현할 수 있고,

public static T 합계<T>(this IEnumerable<T> arg) where T : INumber<T>
{
    T sum = T.Zero;

    foreach (T item in arg)
    {
        sum = sum + item;
    }

    return sum;
}

원하는 만큼 관련 기능을 이런 식으로 추가할 수 있습니다.

List<int> list = new List<int>();

list.AddRange(new[] { 1, 2 });
Console.WriteLine(list.합계());
Console.WriteLine(list.산술평균());

public static float 산술평균<T>(this IEnumerable<T> arg) where T : INumber<T>
{
    return 산술평균<T, float>(arg);
}

public static TResult 산술평균<T, TResult>(this IEnumerable<T> arg) where T : INumber<T>
    where TResult : INumber<TResult>
{
    return TResult.Create(arg.합계()) / TResult.Create(arg.Count());
}

대충 느낌 아시겠죠? ^^

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

현재 Visual Studio 2022 Preview 3.0에서 C# 10 Preview와 System.Runtime.Experimental 어셈블리를 참조 추가한 .NET 6 대상의 프로젝트면 위의 코드를 테스트하는 것이 가능하며, 이는 csproj의 내용에 다음의 설정 3가지를 추가하는 것과 같습니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>enable</Nullable>
        <LangVersion>preview</LangVersion>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="System.Runtime.Experimental" Version="6.0.0-preview.7.21377.19" />
    </ItemGroup>

</Project>




참고로, 위에서 구현한 산술평균 메서드를 IDivisionOperators 인터페이스를 이용해 다음과 같이 구현하는 것도 가능합니다.

public static TResult ArithmeticMean<T, TResult>(this IEnumerable<T> arg) where T : INumber<T>, IDivisionOperators<T, int, TResult>
    where TResult : INumber<TResult>
{
    return arg.합계() / arg.Count();
}

하지만, 이것의 반환 값을 float이나 double 등의 값으로 바꾸는 경우에는 호출 시 다음과 같은 오류가 발생합니다.

// 컴파일 오류
// error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'MyLinqExtension.ArithmeticMean<T>(IEnumerable<T>)'. There is no boxing conversion from 'int' to 'System.IDivisionOperators<int, int, float>'.

Console.WriteLine(list.ArithmeticMean());

public static float ArithmeticMean<T>(this IEnumerable<T> arg) where T : INumber<T>,
                IDivisionOperators<T, int, float>
{
    return ArithmeticMean<T, float>(arg);
}

왜냐하면, Int32 타입은 명시적으로 IDivisionOperators<int, int, int> 인터페이스를 상속받기 때문에 위와 같이 TResult의 타입을 float으로 주는 경우 형변환 오류가 발생하는 것입니다. 마이크로소프트도 아마 저 문제를 인식했기 때문에 이를 우회하기 위해 INumber<T>.Create 메서드를 제공하게 된 것이 아닌가... 추측해 봅니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/15/2022]

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

비밀번호

댓글 작성자
 



2022-06-17 09시03분
.NET 6 Preview에 모습을 나타내고 정식 버전에서는 누락되었다가 다시 .NET 7 Preview에 추가되었습니다. ^^

.NET 7 Preview 5 – Generic Math
; https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/
정성태

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13370정성태6/14/20233288개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233085개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233222개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233320오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233111.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232883오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233665.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233232스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233153.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233608오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233020오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233341오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233633.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233455.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233751DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233663.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233924.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233544.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234055VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233317오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233640.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233565.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233923.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233757오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235018.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236306.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...