本文介绍了在Haskell中传递函数签名中的任何类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个通配符或任何类型的函数,甚至是一种在多种类型之间进行选择的方法,而不仅仅是将其限制为字符串,数字或布尔值,例如:

I want to pass a function a wildcard or any type or even a way to choose between either of multiple types rather than just restrict it to String, or Number, or Boolean, for example:

myFunction :: a -> String

myFunction :: _ -> String

myFunction :: (String || Number) -> String

有可能吗?

推荐答案

myFunction :: a->字符串在技术上是可能的,但是它根本没用,因为它必须能够处理任何类型的参数 ,因此您实际上无法对该参数做任何事情.(这有点像用完全未指定的物质来获得一个罐子–如果它具有腐蚀性,您将不会食用;如果它是脂肪,油漆或胶水,则不能将其用于清洁目的,您无法进一步加工它....如果是不受限制的Haskell类型,您甚至无法分析.)

myFunction :: a -> String is technically possible, however it's profoundly useless – since this must be able to deal with an argument of any type, there's nothing you can actually do with the argument. (It's a bit like getting a can with a completely unspecified substance – you wouldn't eat it in case it's corrosive, you couldn't use it for cleaning purposes in case it's fat, paint or glue, you couldn't process it further... in case of an unrestricted Haskell type you couldn't even analyse it.)

如果将其范围缩小到支持某种常见操作的类型,则多态参数可能有意义:

If you narrow it down to types that support some kind of common operation, a polymorphic argument can make sense:

myFunction' :: Show a => a -> String
myFunction' x = "The value is " ++ show x

您的其他方法也仅支持两种非常具体的类型,这也是可能的:

Your other approach, supporting only two very specific types, is also possible:

myFunction'' :: Either String Integer -> String
myFunction'' (Left s) = "Got a string: "" ++ s ++ """
myFunction'' (Right n) = "Got a number: " ++ show n

请注意,这两种方法完全不同: Show a =>a->字符串可用作 String->字符串 Integer->字符串,或者实际上是支持 show 操作(包括您自己的新定义的类型),但是您必须在编译时确定所需的类型.然后,在运行时,传递给该函数的所有参数都必须具有相同的类型.

Note that these two approaches are quite different: Show a => a -> String can be used as String -> String or as Integer -> String, or in fact any other type which supports the show operation (including newly-defined types of your own), but you must decide at compile-time which type you want. At runtime, all arguments passed to this function must then have the same type.

任何一个字符串整数->字符串可以在运行时接受 String -和 Integer 值的混合,但始终仅限于这两种类型.

Either String Integer -> String can accept a mixture of String- and Integer values at runtime, but is always restricted to only these two types.

这篇关于在Haskell中传递函数签名中的任何类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:11