简体   繁体   中英

How to define a type that represents a Unit type in Haskell?

Suppose I have a function fail'

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

I want to define a function failOrNum which is a lazy function.

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?

I want to achieve something similar to Scala approach:

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. You would probably be better suited by a type with more easily distinguishable inhabitants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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