说我有一个计算两个数字之和的函数:
computeSum :: Int -> Int -> Int
computeSum x y = x + y
上述功能中对返回值的控制形式是什么,我只希望求和两个数字,而它们的< strong> sum 是否会非负且必须小于10 ?
我刚刚从命令式开始函数式编程,我们可以在命令式编程中简单检查一下函数的返回值,例如:
if value <= 10 and value > 0:
return value
只是想知道haskell中是否有类似的东西?
答案 0 :(得分:7)
通常使用assert :: Bool -> a -> a
assert False _ = error "Assertion failed!"
assert _ a = a
来指定“可能失败”的计算,例如:
Maybe
因此,如果断言匹配,它将返回computeSum :: Int -> Int -> Maybe Int
computeSum x y | result > 0 && result <= 10 = Just result
| otherwise = Nothing
where result = x + y
;如果不满足断言,它将返回Just result
。
有时Nothing
用于提供错误消息,例如:
Either String a
您还可以提出一个错误,但是我个人认为这是不明智的,因为签名不会“提示”计算可能失败:
computeSum :: Int -> Int -> Either String Int
computeSum x y | result > 0 && result <= 10 = Right result
| otherwise = Left "Result is note between 0 and 10"
where result = x + y
答案 1 :(得分:3)
是的,Hoogle告诉我们export class AuthGuard implements CanActivate, OnInit {
constructor(private galleryService: GalleryService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.galleryService.auth();
}
ngOnInit() {
}
}
提供了assert :: Bool -> a -> a
。
但是你可以自己写:
Control.Exception
答案 2 :(得分:3)
是的,Haskell具有if语句:
function x y =
let r = x + y
in if r > 0 && r <= 10
then r
else error "I don't know what I'm doing."