나는 C#에서 Maybe 모나드의 장난감 구현을 가지고 있고 관련 SelectMany 확장 메서드를 구현하여 Linq와 함께 작동합니다. IEnumerable과 IMaybe를 하나의 Linq 문에 섞으려고 할 때 문제가 발생했습니다. 내 프로그램이 파일을 읽을 URI 항목의 숫자로 컨텐츠를 구문 분석을 시도하고, 각 항목에 대한 URI에서 콘텐츠를 다운로드 단일 Linq 표현식에서 모나드 구문을 혼합하는 방법은 무엇입니까?
public interface IMaybe<T>
{
bool HasValue { get; }
T Value { get; }
}
public static class Maybe
{
class SomeImpl<T>: IMaybe<T> // obvious implementation snipped for brevity
class NoneImpl<T>: IMaybe<T> // obvious implementation snipped for brevity
// methods to construct the Maybe monad
public static Wrap<T> Some<T>(T value);
public static Wrap<T> Some<T>(T? value) where T: struct;
public static IMaybe<T> None<T>();
public static IMaybe<B> SelectMany<A, B>(this IMaybe<A> a, Func<A, IMaybe<B>> mapFn)
{
if (a.HasValue)
return mapFn(a.Value);
else
return None<B>();
}
public static IMaybe<C> SelectMany<A, B, C>(
this IMaybe<A> a, Func<A, IMaybe<B>> mapFn, Func<A, B, C> selector)
{
if (a.HasValue)
{
var b = mapFn(a.Value);
if (b.HasValue)
return Some(selector(a.Value, b.Value));
else
return None<C>();
}
else
return None<C>();
}
}
처럼
어쩌면 모나드 보인다. 이러한 작업이 정확히 어떻게 구현되는지는 관련이 없습니다. 내가 가지고있는 문제는 Linq 문에서 이러한 작업을 연결하는 데 있습니다. 나는.
static IMaybe<string> ReadFile(string path);
static IMaybe<KeyValuePair<string, Uri>[]> ParseEntries(string input);
static IMaybe<string> Download(Uri location);
static void Main(string[] args)
{
var result = // IEnumerable<IMaybe<anonymous type of {Key, Content}>>
from fileContent in ReadFile(args[0])
from entries in ParseEntries(fileContent)
from entry in entries // this line won't compile
from download in Download(entry.Value)
select new { Key = entry.Key, Content = download };
// rest of program snipped off for brevity
}
오류는 IMaybe와 IEnumerable 모나드를 혼합하는 것에 대해 불평합니다. 정확한 표현에서 :
오류 1 유형의 표현 'System.Collections.Generic.KeyValuePair은 []'소스 유형 'MonadicSharp.IMaybe'와 쿼리 식의 절에서 다음에서 허용되지 않습니다. 'SelectMany'호출에서 형식 유추가 실패했습니다. C : \ Dev \ Local \ MonadicSharp \ MonadicSharp \ Program.cs 142 31 MonadicSharp
어떻게이 문제를 해결할 수 있습니까?
아마도 여기서는 내 지식의 한계를 맞고 있습니다. 나는 모나드 변압기와 하스켈에 관해 읽으 러 돌아갈 것이다. 나는 단서를 얻을 때이 질문에 대해 더 언급 할 것이다. – Ben
약간의 힌트 -'IMaybe'을 피하고 간단히 'Maybe '의 구체적인 유형을 지정하면됩니다. 많은 것들이'IEnumerable '을 구현할 수 있지만,'IMaybe '의 여러 구현에 대한 필요성을 생각할 수 없다. 너는 할수 있니? –
Enigmativity