首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在这种情况下如何使用mapM_

在这种情况下如何使用mapM_
EN

Stack Overflow用户
提问于 2019-09-14 09:47:45
回答 2查看 215关注 0票数 3

我正在尝试在不同的行上打印autocorrelation结果的不同组成部分:

代码语言:javascript
复制
import Data.Vector as V
import Statistics.Autocorrelation
import Data.Typeable

sampleA = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4]

main = do
    let res = autocorrelation $ V.fromList sampleA
    putStr "Type of result of autocorrelation test: "
    print $ typeOf res
    print res
    -- Prelude.mapM_ print res      -- not working; 

输出为:

代码语言:javascript
复制
Type of result of autocorrelation test: ((Vector Double),(Vector Double),(Vector Double))

([1.0,2.5e-2,-0.45,-0.325,0.5,0.125,-0.15],[1.0,-1.3255000000000001,-1.4039375473415425,-1.442999810318651,-1.5311377955236107,-1.5364636906417393,-1.544097864842309],[1.0,1.0755000000000001,1.1539375473415425,1.192999810318651,1.2811377955236107,1.2864636906417393,1.294097864842309])

但是,如果我取消对最后一行的注释,我会得到错误:

代码语言:javascript
复制
• No instance for (Foldable ((,,) (Vector Double) (Vector Double)))
    arising from a use of ‘Prelude.mapM_’
• In a stmt of a 'do' block: Prelude.mapM_ print res
  In the expression:
    do { let res = autocorrelation $ fromList sampleA;
         putStr "Type of result of autocorrelation test: ";
         print $ typeOf res;
         print res;
         .... }
  In an equation for ‘main’:
      main
        = do { let res = ...;
               putStr "Type of result of autocorrelation test: ";
               print $ typeOf res;
               .... }

如何在单独的行上打印结果的所有部分?谢谢你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2019-09-14 09:51:14

最简单的事情就是模式匹配。

代码语言:javascript
复制
main = do
    let (a,b,c) = autocorrelation $ V.fromList sampleA
    print a
    print b
    print c
票数 5
EN

Stack Overflow用户

发布于 2019-09-14 11:55:43

如果你真的不想自己进行模式匹配,你可以使用the fixed-vector package来帮助你。请注意,它有自己的mapM_,您必须使用它:

代码语言:javascript
复制
import Data.Vector as V
import qualified Data.Vector.Fixed as F
import Statistics.Autocorrelation
import Data.Typeable

sampleA = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4]

main = do
    let res = autocorrelation $ V.fromList sampleA
    putStr "Type of result of autocorrelation test: "
    print $ typeOf res
    print res
    F.mapM_ print res

或者,您可以创建一个newtype并将您的元组放在其中:

代码语言:javascript
复制
{-# LANGUAGE DeriveFoldable #-}

import Data.Vector as V
import Statistics.Autocorrelation
import Data.Typeable

newtype Triple a = Triple (a, a, a) deriving(Foldable)

sampleA = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4]

main = do
    let res = autocorrelation $ V.fromList sampleA
    putStr "Type of result of autocorrelation test: "
    print $ typeOf res
    print res
    Prelude.mapM_ print $ Triple res
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57931873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档