Free Pascal 有像 Haskell 那样的类型变量吗?
Haskell 允许您定义像 thrice 这样的函数,它接受 a
类型的元素,并为任何数据类型 a
返回重复三次的元素列表。
thrice :: a -> [a]
thrice x = [x, x, x]
Free Pascal 允许类型变量吗?如果没有,在 Free Pascal 中还有其他方法可以做到这一点吗?
Haskell lets you define functions like thrice, which accepts an element of type a
and returns a list of the element repeated three times, for any data type a
.
thrice :: a -> [a]
thrice x = [x, x, x]
Does Free Pascal allow type variables? If not, is there another way to do this in Free Pascal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为一个不了解 Pascal 的 haskell 人,这似乎是类似的事情。抱歉无法扩展。
http://wiki.freepascal.org/Generics
As a haskell person who doesn't know Pascal, this appears to be a similar thing. Sorry for not being able to expand.
http://wiki.freepascal.org/Generics
不幸的是 FreePascal 目前只有泛型类,没有泛型函数。不过,你的目标仍然可以实现,尽管有点尴尬。您需要定义一个新类来封装您的操作:
现在,不幸的是,当您想要将此类与任何特定类型一起使用时,您需要对其进行专门化:
您才能将其用作:
只有这样 瞧,Pascal 还不是泛型编程的最佳选择。
Unfortunately FreePascal currently has only generic classes, not generic functions. Though, your goal can still be achieved, albeit a little awkwardly. You need to define a new class to encapsulate your operation:
Now, unfortunately when you want to use this class with any specific type, you need to specialize it:
Only then you can use it as:
As you see, Pascal is not the way to go for generic programming yet.
……来自未来的回答。
FreePascal 支持类之外的通用函数和过程。
下面的代码显示了如何将 Thrice 实现为 Times 的特例,同时也说明了您对“FourTimes、FiveTimes 等”的询问。
该代码包括几个使用不同类型(整数、字符串、记录)的示例:
...answering from the future.
FreePascal has support for generic functions and procedures outside of classes.
Here's code that shows how you could implement Thrice as a special case of Times to also illustrate your ask about "FourTimes, FiveTimes, etc.".
The code includes a couple of examples using different types (integer, string, record):