将类型作为参数传递给Haskell中的函数? [英] Pass Types as arguments to a function in Haskell?

查看:109
本文介绍了将类型作为参数传递给Haskell中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个功能非常相似。他们从[String] n个元素中读取[Int]或[Float]。我怎样才能将通用代码分解出来?我不知道Haskell中支持传递类型作为参数的任何机制。

  readInts n stream = foldl next([] ,流)[1..n] 
其中
next(lst,x:xs)_ =(lst ++ [v],xs)
其中
v = read x :: Int

readFloats n stream = foldl next([],stream)[1..n]
其中
next(lst,x:xs)_ =(lst ++ [v],xs)
其中
v = read x :: Float

我在Haskell的初学者级别,所以对我的代码的任何评论都是值得欢迎的。

解决方案

Haskell支持高度的多态性。特别是

  readAny n stream = foldl next([],stream)[1..n] 
其中
next(lst,x:xs)_ =(lst ++ [v],xs)
where
v = read x

有类型

  readAny ::(Enum b,Num b,阅读a)=> b  - > [字符串]  - > ([a],[String])

因此

  readInts ::(Enum b,Num b,Read a)=> [字符串]  - > ([Int],[String])
readInts = readAny

readFloats ::(Enum b,Num b,Read a)=> [字符串] - > ([Float],[String])
readFloats = readAny

你不需要专门方式。 Haskell会自动推断出最普​​通的类型,这里的 readAny 会做你想要的。



不可能在Haskell中传入类型作为参数。你很少会需要。对于那些需要的情况,您可以通过传递一个具有所需类型的值来模拟行为。

Haskell具有返回类型多态性,所以您真的不应该担心通过类型 - 可能性是功能将做你想要的东西,而你告诉他们。


The following two functions are extremely similar. They read from a [String] n elements, either [Int] or [Float]. How can I factor the common code out? I don't know of any mechanism in Haskell that supports passing types as arguments.

readInts n stream = foldl next ([], stream) [1..n]
  where
    next (lst, x:xs) _ = (lst ++ [v], xs)
      where
        v = read x :: Int

readFloats n stream = foldl next ([], stream) [1..n]
  where
    next (lst, x:xs) _ = (lst ++ [v], xs)
      where
        v = read x :: Float

I am at a beginner level of Haskell, so any comments on my code are welcome.

解决方案

Haskell supports a high degree of polymorphism. In particular

readAny n stream = foldl next ([], stream) [1..n]
  where
    next (lst, x:xs) _ = (lst ++ [v], xs)
      where
        v = read x 

has type

readAny :: (Enum b, Num b, Read a) => b -> [String] -> ([a], [String])

thus

readInts :: (Enum b, Num b, Read a) => [String] -> ([Int], [String])
readInts = readAny

readFloats :: (Enum b, Num b, Read a) => [String] -> ([Float], [String])
readFloats = readAny

you dont need to specialize the type. Haskell will automatically infer the most general type possible, and the readAny here will do what you want.

It is not possible to pass types as arguments in Haskell. Rarely would you need to. For those few cases where it is necessary you can simulate the behavior by passing a value with the desired type.

Haskell has "return type polymorphism" so you really shouldn't worry about "passing the type"--odds are that functions will do what you want without you telling them to.

这篇关于将类型作为参数传递给Haskell中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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