在for循环中使用持久对象F#

时间:2016-03-01 17:23:46

标签: f# roslyn

我正在尝试在F#中使用Roslyn对象。我不知道如何在循环中修改对象。

ClassDeclarationSyntax有一个持久的API。每次修改对象时,它都会返回一个新对象。我不知道如何在F#中使用它。

let addPublicProperties (cls: ClassDeclarationSyntax) (props: Map<string, string>)=
for KeyValue(k, v) in props do
    (cls.AddMembers(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(k), v)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))))
cls

看起来像折叠是使这项工作的关键

let addPublicProperties (cls: ClassDeclarationSyntax) (props: Map<string, string>)=
    Map.fold (fun (state:ClassDeclarationSyntax) key (value:string) -> 
       (state.AddMembers(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(key), value)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))))) cls props

2 个答案:

答案 0 :(得分:0)

只是在黑暗中刺伤。

let addPublicProperties (cls: ClassDeclarationSyntax) (props: Map<string, string>)=
    props |> Seq.iter (fun (k,v) -> 
        cls.AddMembers(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(k), v)
            .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) |> ignore)
    cls

如果这不起作用,请尝试使用(k,v)替换KeyValue(k,v)

答案 1 :(得分:0)

Map.fold似乎有我正在寻找的行为。它循环遍历道具地图值。并传递给lambda的附加参数(我将其命名为state,如文档中的示例所示)。每次调用lambda时都会传递此状态。根据结果​​判断,lambda的返回值成为状态。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/3.5.3/iframeResizer.js"></script>

<!--3. SOLUTION HTML ATTRIBUTES - NOT WORKING-->
<div style="margin:0px;padding:0px;overflow:hidden">
  <iframe id="frame" src="https://fiddle.jshell.net" sandbox="allow-same-origin allow-scripts" style="width:100%; height: 100%; overflow:hidden" frameborder="1" scrolling="no" height="100%" width="100%" seamless="seamless"></iframe>
</div>

<div id="content">
  <a href="javascript:void(0);" id="add">Add</a>
  <a href="javascript:void(0);" id="remove">Remove</a>
  <ul id="sortable" class="sortable">
    <li>ITEM</li>
    <li>ITEM</li>
    <li>ITEM</li>
    <li>ITEM</li>
    <li>ITEM</li>
    <li>ITEM</li>
    <li>ITEM</li>
    <li>ITEM</li>
  </ul>
</div>