Haskell:使用patten匹配currying数据

时间:2016-01-22 17:27:00

标签: haskell currying

是否可以使用patten匹配currying数据?假设以下代码:

data Bind = Echo String | Sum Int Int

getOperation (Echo  x )  =  "Echo"
getOperation (Sum  x y ) = "Sum"

main = getOperation (Sum 1)

失败,因为Sum 1的类型为Int -> Bind,而getOperation的类型为Bind -> String

我的目的是获取一个字符串,即使数据是咖喱的,也会使用过的数据构造函数。像这样的假代码:

getOperation (Echo  x )  =  "Echo"
getOperation (Echo) = "Echo"       -- Pattern matching for curried data
getOperation (Sum  x y ) = "Sum"
getOperation (Sum x) = "Sum"       -- Pattern matching for curried data

1 个答案:

答案 0 :(得分:1)

将名称附加到值是没有问题的。

data Named a = Named { name :: String, value :: a }

-- there is a very natural Functor instance for Named as well, which
-- could be used to implement this
(<$$>) :: Named (a -> b) -> a -> Named b
Named n f <$$> x = Named n (f x)

以下是如何使用它的示例:

data Bind = Echo String | Add Int Int

echo :: Named (String -> Bind)
add  :: Named (Int -> Int -> Bind)
add  = Named "Add" Add
echo = Named "Echo" Echo

main = do
    putStrLn . name $ echo
    putStrLn . name $ echo <$$> "hi"
    putStrLn . name $ add
    putStrLn . name $ add <$$> 3
    putStrLn . name $ add <$$> 3 <$$> 4

这会产生:

Echo
Echo
Add
Add
Add