Defining function signature in GHCi

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 11:57:39

You can define a function signature in the ghc interactive shell. The problem however is that you need to define functions in a single command.

You can use a semicolon (;) to split between two parts:

Prelude> square :: Int -> Int; square x = x * x

Note that the same holds for a function with multiple clauses. If you write:

Prelude> is_empty [] = True
Prelude> is_empty (_:_) = False

You have actually overwritten the previous is_empty function with the second statement. If we then query with an empty list, we get:

Prelude> is_empty []
*** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty

So ghci took the last definition as a single clause function definition.

Again you have to write it like:

Prelude> is_empty[] = True; is_empty (_:_) = False

Multi-line input needs to be wrapped in the :{ and :} commands.

λ> :{
 > square :: Int -> Int
 > square x = x * x
 > :}
square :: Int -> Int

Here are three ways:

>>> square :: Int -> Int; square = (^2)
>>> let square :: Int -> Int
...     square = (^2)
...
>>> :{
... square :: Int -> Int
... square = (^2)
... :}

The second one requires you to :set +m; I include this in my ~/.ghci so that it is always on.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!