Jim*_*ffa 1 erlang functional-programming anonymous-function
我一直在环顾四周,无法找到这方面的例子,我的所有语法摔跤技巧都让我失望.有谁能告诉我如何编译?我的s,s或.s是错误的我想定义一个嵌套函数...
我知道有一个函数可以进行字符串替换,所以我不需要实现这个,但是我正在玩Erlang试图把它拿起来所以我手动旋转我需要使用的一些基础知识. .
replace(Whole,Old,New) ->
OldLen = length(Old),
ReplaceInit = fun(Next, NewWhole) ->
if
lists:prefix(Old, [Next|NewWhole]) -> {_,Rest} = lists:split(OldLen-1, NewWhole), New ++ Rest;
true -> [Next|NewWhole]
end,
lists:foldr(ReplaceInit, [], Whole).
Run Code Online (Sandbox Code Playgroud)
基本上我正在尝试写这个haskell(也可能是坏的,但超出了这一点):
repl xs ys zs =
foldr replaceInit [] xs
where
ylen = length ys
replaceInit y newxs
| take ylen (y:newxs) == ys = zs ++ drop (ylen-1) newxs
| otherwise = y:newxs
Run Code Online (Sandbox Code Playgroud)
主要问题是,if你只能使用警卫作为测试.防护是非常有限的,除其他外,不允许调用一般的Erlang函数.无论它们是OTP版本的一部分还是由您撰写.您的功能的最佳解决方案是使用case而不是if.例如:
replace(Whole,Old,New) ->
OldLen = length(Old),
ReplaceInit = fun (Next, NewWhole) ->
case lists:prefix(Old, [Next|NewWhole]) of
true ->
{_,Rest} = lists:split(OldLen-1, NewWhole),
New ++ Rest;
false -> [Next|NewWhole]
end
end,
lists:foldr(ReplaceInit, [], Whole).
Run Code Online (Sandbox Code Playgroud)
因为if在Erlang中经常没有使用它.请参阅有关if与大约警卫 Erlang的文档.
| 归档时间: |
|
| 查看次数: |
1673 次 |
| 最近记录: |