Opa:遍历stringmap并根据它形成一个新的字符串 [英] Opa: Iterating through stringmap and forming a new string based on it
问题描述
我正在编辑Opa文档中的 Hello-wiki 代码.我希望Wiki主题具有数据库中现有主题的列表.我有一个在默认主题上调用的函数:
I'm editing the Hello-wiki code from Opa Documentation. I want a wiki-topic to have a list of the existing topics in the database. I have a function which is called on the default topic:
/**
* Collect all created topics from /wiki
* and present them in Markdown format
*/
function collect_topics(page) {
string collection = "#Available topics\n"
// Format as a list
Set.iter(function( topic ) {
collection = "{collection} *[{topic}](./{topic})\n"
}, [/wiki])
save_source(page, collection)
}
...
function start(url) {
match (url) {
case {path: [] ... } :
{ collect_topics("Topics") };
case {~path ... } :
{ display(String.capitalize(String.to_lower(String.concat("::", path)))) };
}
}
据我理解,这会引起语法错误:找到一个绑定作为条件",因为字符串是不可变的.有没有办法更改创建的字符串?例如:
This raises a syntax error: "found a binding as condition", to my understanding because strings are immutable. Is there a way to change a created string? For example:
string x = "foo"
x = x ^ x
万一这是不可能的,那有什么更好的方法?
In case this is impossible, what would be a better approach?
推荐答案
Inded Opa是一种功能编程语言,其值不可更改.如果您确实想要可变的值,请使用 http://doc.opalang.org/module/stdlib.core/Mutable 或Cells来处理应用程序
Indeed Opa is a functional programming language, values are not mutable. If you really want a mutable value, use http://doc.opalang.org/module/stdlib.core/Mutable or Cells to handle states (with safe updates) on your app http://doc.opalang.org/value/stdlib.core.rpc.core/Cell/make
这是编写代码的方式:
function collect_topics(page) {
collection =
Map.fold(function( key, value, acc ) {
"{acc}\n *[{key}](./{value})"
}, /wiki, "#Available topics\n")
collection
}
在这里,我使用Set.fold而不是Set.iter. List.fold文档应该可以帮助您了解"fold"功能的工作原理: http://doc.opalang.org/value/stdlib.core/List/fold
Here I use Set.fold instead of Set.iter. The List.fold documentation should help your to understand how "fold" functions works: http://doc.opalang.org/value/stdlib.core/List/fold
Set.iter不返回任何内容(无效),它仅用于遍历集合并产生一些副作用,例如在控制台中打印日志,修改Dom等
Set.iter doesn't return anything (void), it's only used to iterate through the collection and do some side-effects, like printing log in the console, modifying the Dom, etc
这篇关于Opa:遍历stringmap并根据它形成一个新的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!