我需要什么类型的签名来允许将函数列表转换为haskell代码? [英] What type signature do I need to allow a list of functions to be converted to haskell code?

查看:89
本文介绍了我需要什么类型的签名来允许将函数列表转换为haskell代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

为什么在haskell中不允许这样的函数定义?

Possible Duplicate:
Why is such a function definition not allowed in haskell?

我做了一个名为 funlist 的haskell函数。它的作用是获取一个初始值和一个函数列表,并将列表中的所有函数应用于初始值。

I made a haskell function called funlist. What it does is it takes a starting value, and a list of functions, and applies all of the functions in the list to the starting value.

funlist thing [function] = function thing
funlist thing (function:functions) = funlist (function thing) functions
funlist _ _ = error "need a list of functions"

这个函数的问题在于它有一个 funlist :: t - > [t - > t] - >吨。该类型意味着虽然ghc将允许不将起始值转换为完全不同类型的函数列表(例如 [sin,cos,tan] )将被允许),将起始值转换为不同类型的函数(例如 show )会生成一个错误,因为该函数与类型签名不匹配。

The problem with this function is that it has a type of funlist :: t -> [t -> t] -> t. That type means that while ghc will allow a list of functions that don't convert the starting value to a completely different type (e.g [sin,cos,tan] will be allowed), a function that converts the starting value to a different type (e.g show) will generate an error because that function doesn't match the type signature.

这不是函数应该如何工作的。它应该能够获取改变起始值类型的函数列表(例如 [sin,show] )。该函数基本上将 funlist 5 [sin,cos,tan,isInfinite,show] 转换为 show $ isInfinite $ tan $ cos $ sin $ 5 ,而后者的工作,前者不会。

This isn't how the function should work. It should be able to take a list of functions that change the starting values type (e.g. [sin,show]). This function basically converts funlist 5 [sin,cos,tan,isInfinite,show] to show $ isInfinite $ tan $ cos $ sin $ 5, and while the latter works, the former doesn't.

有什么方法可以让这个函数正常工作吗?

Is there any way that I can get this function to work properly?

编辑:我知道>>> ; ,我只是想知道是否有办法让这个工作。

I know about . and >>>, I'm just wondering if there's a way to make this work.

推荐答案

使用GADT编写您想要的内容:

You can write what you want with a GADT:

{-# LANGUAGE GADTs #-}
module Funlist where

data F x y where
  Id :: F a a
  Ap :: (a->b) -> F b c -> F a c

-- A very round about way to write f x = x + x

f1 :: Int -> Char
f1 = toEnum

f2 :: Char -> String
f2 x = x:x:[]

f3 :: String -> [Int]
f3 = map fromEnum

f4 :: [Int] -> Integer
f4 = foldr (+) 0 . map toInteger

f_list :: F Int Integer
f_list = Ap f1 (Ap f2 (Ap f3 (Ap f4 Id)))

ap :: F a b -> a -> b
ap Id x = x
ap (Ap f gs) x = ap gs (f x)

现在 ap f_list 65 130

这篇关于我需要什么类型的签名来允许将函数列表转换为haskell代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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