给定函数g :: a - > b - > .... - > z,如何使用它像h ::(a,b,...) - > Z'

时间:2015-12-05 03:19:26

标签: haskell currying wxhaskell

背景:我正在使用wxHaskell的fileOpenDialog,它有6个非显而易见的参数(curried)。我的代码目前是:

maybePath <- fileOpenDialog w useLastSelectedDir canSelectReadOnly
                frameName possibleFiles initialDir defaultFilename

上面有一个let语句来定义我的所有参数。我喜欢做的是在某处保存我的参数。我有点理解为什么Haskell会支持像:

这样的东西
myParams = ( ... ) -- tuple of params
maybePath <- fileOpenDialog myParams

然而,有没有接近这一点的本着不重复自己的精神?

2 个答案:

答案 0 :(得分:2)

看起来您自然希望此函数的输入成为参数记录:

{-# LANGUAGE RecordWildCards #-} 

-- Defined by your library 
foo :: String -> Int -> IO () 
foo = ... 

data Opts = Opts { optString :: String, optInt :: Int } 
bar :: Opts -> IO () 
bar Opts{..} = foo optString optInt 

现在,您可以使用以下任何等效语法(一些使用RecordWildCards):

main = do 
  let optString = <...>
      optInt    = <...>
  bar Opts{..} 

main = do 
  let x = <...>
      y = <...>
      myParams = Opts x y 
  bar myParams 

main = do 
  bar $ Opts 
    { optString = <...> 
    , optInt    = <...> 
    } 

main = do 
  let optString = <...>
      optInt    = <...>
      myParams  = Opts{..} 
  bar myParams 

答案 1 :(得分:1)

还有(不太干净)编写uncurry变体(见here)有更多参数的可能性:

uncurry6 :: (a -> b -> c -> d -> e -> f -> g) -> ((a,b,c,d,e,f) -> g)
uncurry6 fun (a,b,c,d,e,f) = fun a b c d e f 

有了这个,uncurry6 fileOpenDialog会使fileOpenDialog接受6元组。