可能的重复:
为什么 haskell 中不允许这样的函数定义? https://stackoverflow.com/questions/6168880/why-is-such-a-function-definition-not-allowed-in-haskell
我做了一个名为的 haskell 函数funlist
。它的作用是获取一个起始值和一个函数列表,并将列表中的所有函数应用于起始值。
funlist thing [function] = function thing
funlist thing (function:functions) = funlist (function thing) functions
funlist _ _ = error "need a list of functions"
这个函数的问题是它有一个类型funlist :: t -> [t -> t] -> t
。该类型意味着虽然 ghc 将允许不将起始值转换为完全不同类型的函数列表(例如[sin,cos,tan]
将被允许),将起始值转换为不同类型的函数(例如show
) 将生成错误,因为该函数与类型签名不匹配。
这不是该函数应该如何工作的。它应该能够获取更改起始值类型的函数列表(例如[sin,show]
)。这个函数基本上转换funlist 5 [sin,cos,tan,isInfinite,show]
to show $ isInfinite $ tan $ cos $ sin $ 5
,虽然后者有效,但前者无效。
有什么办法可以让这个功能正常工作吗?
EDIT:我知道关于.
and >>>
,我只是想知道是否有办法使这项工作有效。
您可以使用 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)
Now ap f_list 65
is 130
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)