mat*_*ias 2 haskell type-conversion
我怎样写一个函数,作为输入Int,并返回Int,如果它是> 0或以其他方式返回一个破折号"-",如果它是< 0.我知道Haskell对它的类型很严格,但有没有办法解决这个问题呢?
Haskell是静态类型的,这意味着通常您无法根据运行时内容更改类型.
但是你可以使用以下Either类型:
fun :: Int -> Either Int String
fun x | x > 0 = Left x
| otherwise = Right "-"
Run Code Online (Sandbox Code Playgroud)
Either 定义为:
data Either a b = Left a | Right b
Run Code Online (Sandbox Code Playgroud)
然后,您可以在程序中查询是否正在处理左构造函数或正确的构造函数.
我认为Haskell这样做的方法就是使用Maybe.
positive :: Int -> Maybe Int
positive x | x >= 0 = Just x
| x < 0 = Nothing
Run Code Online (Sandbox Code Playgroud)
然后,你可以模式匹配,看看你是否有一个Just或一个Nothing.否则,没有办法编写一个能够完成你所说的功能 - 它的签名是什么:Int -> Int或者Int -> String?
haskell中的函数需要返回单个类型.你可以争论这是否有益(参见这篇Programmers.SE文章)但是如果不深入研究语言的更复杂部分,那么你必须处理它.
就像评论中提到的@pdexter和答案中提到的@Alec一样,a Maybe 是解决这个问题的最好方法.
import Data.Maybe
...
f :: Int -> Maybe Int
f num
| x >= 0 = Just num
| x < 0 = Nothing
Run Code Online (Sandbox Code Playgroud)
然后在您的其他代码中,您可以处理Maybe:
-- Let's assume you want to bind the result to a String type
let num = f Number
putStrLn $ case num of
Just x -> show x
Nothing -> "-"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |