我是Haskell的新手,也是一般的编程.我试图定义一个从n生成Collatz数字序列的函数.我有:
collatz n = (collatz' n) : 1
where collatz' n = (takeWhile (>1) (collatz'' n))
where collatz'' n = n : collatz'' (collatz''' n)
where collatz''' 1 = 1
collatz''' n = if (even n) then (div n 2) else ((3*2)+1)
Run Code Online (Sandbox Code Playgroud)
当我在GHCi中运行它时,我收到错误:
No instance for (Num [t])
arising from the literal `2' at <interactive>:1:7
Possible fix: add an instance declaration for (Num [t])
Run Code Online (Sandbox Code Playgroud)
我不知道这意味着什么.问题似乎是在列表中追加"1".出现这个问题是因为
collatz' n = (takeWhile (>0) (collatz'' n))
Run Code Online (Sandbox Code Playgroud)
在正确的Collatz序列之后产生无限的"1"序列; 然而,
collatz' n …Run Code Online (Sandbox Code Playgroud) 作为更大函数定义的一部分,我需要允许函数的域(i,n)以不同的速率从i递增到n.所以我写道:
f (i, n) k = [i, (i+k)..n]
Run Code Online (Sandbox Code Playgroud)
进入GHC.这返回了奇怪的结果:
*Main> f (0.0, 1.0) 0.1
[0.0,0.1,0.2,0.30000000000000004,0.4000000000000001,0.5000000000000001,0.6000000000000001,0.7000000000000001,0.8,0.9,1.0]
Run Code Online (Sandbox Code Playgroud)
为什么GHC会返回,例如0.30000000000000004而不是0.3?
此函数生成简单的.dot文件,以使用Graphviz可视化自动机转换函数.它的主要目的是调试大量自动生成的转换(例如,拉丁语动词的变形).
prepGraph :: ( ... ) => NFA c b a -> [String]
prepGraph nfa = "digraph finite_state_machine {"
: wrapSp "rankdir = LR"
: wrapSp ("node [shape = circle]" ++ (mapSp (states nfa \\ terminal nfa)))
: wrapSp ("node [shape = doublecircle]" ++ (mapSp $ terminal nfa))
: formatGraph nfa ++ ["}"]
formatGraph :: ( ... ) => NFA c b a -> [String]
formatGraph = map formatDelta . deltaTuples
where formatDelta (a, a', bc) = wrapSp (mkArrow a …Run Code Online (Sandbox Code Playgroud) 创建列表或集合的排列很简单.我需要按照它们出现的顺序将一个函数应用于列表中所有元素的所有子集的每个元素.例如:
apply f [x,y] = { [x,y], [f x, y], [x, f y], [f x, f y] }
Run Code Online (Sandbox Code Playgroud)
我的代码是一个可怕的管道或昂贵的计算,我不知道如何继续,或者它是否正确.我确信必须有更好的方法来完成这项任务 - 也许在monad列表中 - 但我不确定.这是我的代码:
apply :: Ord a => (a -> Maybe a) -> [a] -> Set [a]
apply p xs = let box = take (length xs + 1) . map (take $ length xs) in
(Set.fromList . map (catMaybes . zipWith (flip ($)) xs) . concatMap permutations
. box . map (flip (++) (repeat Just)) . flip …Run Code Online (Sandbox Code Playgroud)