在Haskell中循环 [英] Do while loop in Haskell
本文介绍了在Haskell中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数:
isItSimple :: Int - > Bool
得到Int并返回Bool。
我需要在[x |中找到第一个号码x < - [ n .. ],isItSimple x]。
这是我的解决方案:
findIt :: Int - > Int
findIt num
| isItSimple num = num
|否则= findIt(num + 1)
Haskell中有更好的解决方案吗?
解决方案
在大多数情况下,特别是当您的问题是解决问题的特定情况时,显式拒绝是不好的。没有使用显式递归的问题的一个可能的解决方案是:
$ p $ import Data.List(find)
import Data 。可能(从Just)
findIt :: Int - > Int
findIt n = from Just $ find isItSimple [n ..]
I have a function:
isItSimple :: Int -> Bool
it gets Int and return Bool.
I need to find first number in [x | x <- [n..], isItSimple x].
Here is my solution:
findIt :: Int -> Int
findIt num
| isItSimple num = num
| otherwise = findIt (num + 1)
Is there any better solution in Haskell?
解决方案
In most cases, especially when your problem is a particular case of solved one, explicit resursion is bad. One of possible solutions of your problem without using explicit recursion is:
import Data.List (find)
import Data.Maybe (fromJust)
findIt :: Int -> Int
findIt n = fromJust $ find isItSimple [n..]
这篇关于在Haskell中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文