我如何在 Haskell 中定义 Lisp 的应用? [英] How do I define Lisp’s apply in Haskell?

查看:14
本文介绍了我如何在 Haskell 中定义 Lisp 的应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在像 Haskell 这样的函数被柯里化的惰性语言中,难道不应该允许这个定义吗?

Shouldn’t this definition be allowed in a lazy language like Haskell in which functions are curried?

apply f [] = f
apply f (x:xs) = apply (f x) xs

它基本上是一个将给定函数应用于给定参数列表的函数,例如在 Lisp 中很容易完成.有什么解决方法吗?

It’s basically a function that applies the given function to the given list of arguments and is very easily done in Lisp for example. Are there any workarounds?

推荐答案

很难为 apply 函数提供静态类型,因为它的类型取决于(可能是异构的)的类型列表参数.至少有两种方法我能想到的一种在 Haskell 中编写此函数的方法:

It is hard to give a static type to the apply function, since its type depends on the type of the (possibly heterogeneous) list argument. There are at least two ways one way to write this function in Haskell that I can think of:

使用反射

我们可以将应用程序的类型检查推迟到运行时:

We can defer type checking of the application until runtime:

import Data.Dynamic
import Data.Typeable

apply :: Dynamic -> [Dynamic] -> Dynamic
apply f []      = f
apply f (x:xs)  = apply (f `dynApp` x) xs

请注意,现在 Haskell 程序可能会在运行时因类型错误而失败.

Note that now the Haskell program may fail with a type error at runtime.

通过类型类递归

使用半标准的 Text.Printf 技巧(由 augustss, IIRC 发明),可以对解决方案进行编码 以这种方式(练习).虽然它可能不是很有用,但仍然需要一些技巧来隐藏列表中的类型.

Using the semi-standard Text.Printf trick (invented by augustss, IIRC), a solution can be coded up in this style (exercise). It may not be very useful though, and still requires some trick to hide the types in the list.

如果不使用动态类型或 hlists/existentials,我无法想出一种写法.很想看一个例子

这篇关于我如何在 Haskell 中定义 Lisp 的应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆