简体   繁体   English

haskell中的函数单独声明

[英]Separate declaration of functions in haskell

Is there a way (maybe some pragma or extension (I'm using GHC )) that allow to declare different patterns of function separately? 有没有一种方法(也许有些编译指示或扩展名(我正在使用GHC ))允许分别声明不同的功能模式?

For example, I can do that: 例如,我可以这样做:

fun1 1 = "1"
fun1 2 = "a"
fun1 3 = "4"
fun1 4 = "3"

But I can't do that: 但是我不能这样做:

fun1 1 = "1"
fun1 2 = "a"
fun1 3 = "4"

a = 3 -- Just some code here.

fun1 4 = "3"

ie I need something to remove this restriction. 即我需要一些东西来消除这种限制。

I need it in some kind of "game", where the previous code can't be edited. 我需要某种“游戏”来使用它,在此之前的代码无法编辑。

Thank you in advance! 先感谢您!

As far as I know, this is not possible. 据我所知,这是不可能的。 Multiple definitions like this are just syntax sugar over case and thus are not terrifically robust syntactic abstractions. 像这样的多个定义仅是语法case ,因此不是语法上鲁棒的语法抽象。 It's just not normally necessary. 只是通常没有必要。

You may have luck using the haskell-src package to parse Haskell code and build your incremental interface for your game. 使用haskell-src来解析Haskell代码并为您的游戏构建增量界面可能会很幸运。

I can't help feeling that if this were allowed, folk would write rather messy code. 我不禁感到,如果允许的话,人们会编写相当混乱的代码。

Unless there's an important structural reason, it'd be better to stick with the usual valid syntax - it's easier to understand if the definition is all in one place. 除非有重要的结构原因,否则最好坚持使用通常有效的语法-如果定义全部放在一个地方,则更容易理解。

However, perhaps it would be better to structure it differently to achieve what you want: 但是,也许最好以不同的方式构造它以实现所需的功能:

  • You could use Data.Map to build up several submaps in different parts of your code, then glue them all together at some appropriate stage. 您可以使用Data.Map在代码的不同部分构建几个子图,然后在某个适当的阶段将它们粘合在一起。

  • You could keep these definitions in a sort of configuration file or files, and read them in as your game initialised. 您可以将这些定义保存在一个或多个配置文件中,并在游戏初始化时读取它们。 Your users might like the ease of editing the game this way. 您的用户可能喜欢以这种方式轻松编辑游戏。

  • You could store your data in a more Haskell-friendly way 您可以以更方便Haskell的方式存储数据

    • You could serialise it using the binary package, which is fast, and read it in at runtime. 您可以使用快速的二进制包对其进行序列化,然后在运行时读取它。

    • You could use Yesod's backend-agnostic Persistent 您可以使用Yesod的与后端无关的Persistent

    • Too many other options here 这里有太多其他选择

  • You could use a union type (like Either ) for your input to fun1 , and then distribute the definition about the code, but write a unified function that checks the input and tags it according to category. 您可以对fun1的输入使用联合类型(例如Either ),然后分发有关代码的定义,但是编写一个统一的功能来检查输入并根据类别对其进行标记。

It's hard to know what's best without some knowledge of what you're trying to do, but slackening the sytnax rules doesn't feel like a good step forward. 在不了解您要做什么的情况下很难知道什么是最好的,但是放松sytnax规则并不意味着前进了一步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM