我只是与 Haskell 错误搏斗了一个小时,然后将其追溯到特定函数名称的使用it。有人可以解释为什么在下面的成绩单中函数名称fu和it行为不同吗?具体来说,为什么在it调用时类型会发生变化?
?> fu x = x + 1
?> :t fu
fu :: Num a => a -> a
?> fu 1
2
?> :t fu
fu :: Num a => a -> a
?> it x = x + 1
?> :t it
it :: Num a => a -> a
?> it 1
2
?> :t it
it :: Num a => a
Run Code Online (Sandbox Code Playgroud)
当 ghci 重新启动时,它报告it不在范围内,所以我认为 …
你好Haskellers先生.
假设我有一个applicative functor(不是monad的实例)我想多次应用于纯初始值.例如,
?> Just (1+) <*> (Just (1+) <*> pure 0)
Just 2
Run Code Online (Sandbox Code Playgroud)
如果我想将它推广到任意数量的连续应用程序,我可以使用a fold.
applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = foldr (<*>) i $ replicate n f
Run Code Online (Sandbox Code Playgroud)
在这个定义之后,
?> applyAppl (Just (1+)) 10 $ pure 0
Just 10
Run Code Online (Sandbox Code Playgroud)
我有一种尴尬的怀疑,即可以使用其中一个高阶内置应用工具来完成泛化,例如sequenceA或traverse.它可以?
(编辑考虑下面的前两条评论.)
列表monad为搜索问题的回溯提供了极好的抽象.然而,我现在面临的问题是除了回溯之外还涉及状态的问题.(它还涉及与先前在搜索路径中做出的选择相关的约束,但我稍后会解决该问题.)
以下简化示例说明了问题.该函数sumTo被赋予一个非负整数和一个带有整数对的列表.每对中的第一个元素是正整数,第二个元素是可用的这种整数的数量.搜索问题是使用计数约束来使用列表中的整数表达第一个参数.例如,这里整数8以不同的方式表示为五个1s,三个2s和两个
4s的总和,其中所有构成总和的数字必须是偶数(因此1不能使用s).
?> sumTo 8 [(1,5), (4,2), (2,3)]
[[4,4],[4,2,2],[2,2,4],[2,4,2]]
Run Code Online (Sandbox Code Playgroud)
以下是我目前针对该问题的递归解决方案.
sumTo :: Int -> [(Int, Int)] -> [[Int]]
sumTo = go []
where
go :: [(Int, Int)] -> Int -> [(Int, Int)] -> [[Int]]
go _ 0 _ = [[]] -- base case: success
go _ _ [] = [] -- base case: out of options, failure
-- recursion step: use the first option if it has counts left and …Run Code Online (Sandbox Code Playgroud) 使用-Wtype-defaults(附带-Wall),floor . sqrt . fromIntegral即使我指定了参数的类型和结果,也会给我大量警告:
?> (floor . sqrt . fromIntegral) (10 :: Int) :: Int
<interactive>:356:2-6: warning: [-Wtype-defaults]
• Defaulting the following constraints to type ‘Double’
(RealFrac a0)
arising from a use of ‘floor’ at <interactive>:356:2-6
(Floating a0)
arising from a use of ‘sqrt’ at <interactive>:356:10-13
(Num a0)
arising from a use of ‘fromIntegral’ at <interactive>:356:17-28
• In the first argument of ‘(.)’, namely ‘floor’
In the expression: floor . sqrt . fromIntegral …Run Code Online (Sandbox Code Playgroud)