【问题标题】:Translate Haskell code into Standard ML (combinations with repetition)将 Haskell 代码翻译成标准 ML(重复组合)
【发布时间】:2014-12-14 00:46:36
【问题描述】:

我正在为从 k 值的选择中提取的 n 个元素重复排列编写代码。所以我的结果集的基数应该有 k^n 个元素。在 Haskell 中,这相当容易。例如,可以只写:

导入 Control.Monad (replicateM)

main = mapM_ print (replicateM 2 [1,2,3])

然后你会得到一个列表:

[1,1] [1,2] [1,3] [2,1] [2,2] [2,3] [3,1] [3,2] [3,3]

但在标准 ML 上,我不知道该怎么做。

我试过了:

fun combs_with_rep (k,xxs) =

 case (k, xxs) of (0,_) => [[]]
                  |(_, []) => []

                  |(k, x::xs) =>List.map (fn ys => x::ys) (combs_with_rep((k-1),xxs))@ combs_with_rep(k,xs)

但列表不完整,我不知道为什么....

是否有与 Haskell 中相同的模拟编码?或者我应该如何修复我的 sml 代码?

感谢任何帮助!

【问题讨论】:

    标签: algorithm haskell permutation sml


    【解决方案1】:

    只需转换一元代码:

    rep_comb n xs  -- n times choose 1 elem from xs, repetition allowed
      = replicateM n xs 
      = sequence $ replicate n xs
      = foldr k (return []) $ replicate n xs
            where
              k m m' = do { x <- m; xs <- m'; return (x:xs) }
      = case n of 0 -> [[]] ;
                  _ -> k xs (rep_comb (n-1) xs)
            where
              k m m' = m >>= (\x-> 
                       m' >>= (\xs ->  return (x:xs) ))
      = case n of 0 -> [[]] ;
                  _ -> xs >>= (\y-> 
                       rep_comb (n-1) xs >>= (\ys -> [y:ys]))
      -- i.e.
      = case n of 0 -> [[]] ;
                  _ -> [y:ys | y<- xs, ys<- rep_comb (n-1) xs]
      = case n of 0 -> [[]] ;
                  _ -> concatMap  (\y-> map (y:) (rep_comb (n-1) xs))  xs
      -- or, in a different order
      = case n of 0 -> [[]] ;
                  _ -> [y:ys | ys<- rep_comb (n-1) xs, y<- xs]
      = case n of 0 -> [[]] ;
                  _ -> concatMap  (\ys-> map (:ys) xs)  (rep_comb (n-1) xs)
    

    现在您可以将其翻译为 ML。

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 1970-01-01
      • 2014-05-12
      • 2013-02-22
      • 2012-07-05
      • 1970-01-01
      • 2013-11-25
      • 2018-09-09
      • 2015-11-25
      相关资源
      最近更新 更多