简体   繁体   English

如何在Haskell中定义代表单位类型的类型?

[英]How to define a type that represents a Unit type in Haskell?

Suppose I have a function fail' 假设我有一个功能fail'

fail' :: ()
fail' = error "Ka-boom!"

I want to define a function failOrNum which is a lazy function. 我想定义一个函数failOrNum ,它是一个惰性函数。

failOrNum :: () a => (a -> a) -> Num -> Num
failOrNum f n = n + 1

Example: 例:

failOrNum fail' 5

What type of failOrNum function should I specify to satisfy the conditions? 我应该指定哪种类型的failOrNum函数来满足条件?

I want to achieve something similar to Scala approach: 我想实现类似于Scala方法的东西:

object LazyComputation extends App {
  def failOrInt(execution: => Unit, n: Int): Int = n + 1

  println {
    failOrInt({throw new RuntimeException("Ka-boom!")}, 5)
  }
}

It's not 100% clear to me what you want to do. 我不清楚您想做什么。 But one way to fix your syntax and type errors would be like this: 但是,解决语法和类型错误的一种方法是:

fail' :: () -> ()
fail' _ = error "kaboom"
-- OR, to cause errors before this is even applied to an argument,
-- fail' = error "kaboom"
-- these two are distinguishable *only* by the seq function

failOrNum :: Num a => (() -> ()) -> a -> a
failOrNum _ n = n+1

However, I find this a very odd thing to want: there are really only a few semantically distinct inhabitants of () -> () , and most of them are not really usefully distinguishable from within the pure side of Haskell. 但是,我发现这是一件很奇怪的事情: () -> ()确实只有几个语义上不同的居民,而从Haskell的纯粹方面来说,它们中的大多数并没有真正有用的区分。 You would probably be better suited by a type with more easily distinguishable inhabitants. 居民更容易区分的类型可能更适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM